Найти элемент в xml, вставленный пользователем - PullRequest
0 голосов
/ 03 апреля 2020

Привет, я новичок в Python

Я хочу восстановить данные внутри элемента и идентификатор элемента, определенный пользователем, пожалуйста, смотрите мою попытку ниже

спасибо за вашу помощь

import xml.etree.ElementTree as ET
tree = ET.parse('sa.xml')
root = tree.getroot()

segment_id=input()
print(segment_id)
#for y in root[21].findall(".//*[@ID='PG4022R']"):
for y in root[21].find('.//div[@ID="segment_id"]//input'):

идея в том, что пользователь будет вставлять'PG4022R 'в качестве "gment_id "и затем использовать это значение в коде для поиска данных

причина в том, что у меня есть еще один бит код, где мне понадобится этот 'PG4022R', чтобы найти больше данных

for x in root[21].findall(".//*[@ID='segment_id']/Segment-Berth-Route-List"):

Ответы [ 2 ]

0 голосов
/ 03 апреля 2020

Перед выполнением Пожалуйста, обратитесь к этому xml do c: XML Ссылка для этого кода

Вот мой обновленный код: (Просто попробуйте с этим)

import xml.etree.ElementTree as ET
tree = ET.parse('xmlfile.xml')
root = tree.getroot()
l1 = []
a = input('Enter Tag Name : ')
print('The below are the corresponding id of the tag '+a)
for x in root.findall(a):
    item =x.attrib.get('id')
    l1.append(item)
print(l1)
c = input('Enter the ids with , seperated (min 2 ) : ')
d = c.split(',')
print(d)
for y in root.findall(a):
    for z in y:
        if y.attrib.get('id') in d:
            print(z.text)

Вывод:

Enter Tag Name : book
The below are the corresponding id of the tag book
['bk101', 'bk103', 'bk104', 'bk105', 'bk106', 'bk107', 'bk108', 'bk109', 'bk110', 'bk111', 'bk112']
Enter the ids with , seperated (min 2 ) : bk101,bk103,bk104
['bk101', 'bk103', 'bk104']
Gambardella, Matthew
XML Developer's Guide
Computer
44.95
2000-10-01
An in-depth look at creating applications 
      with XML.
Corets, Eva
Maeve Ascendant
Fantasy
5.95
2000-11-17
After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society.
Corets, Eva
Oberon's Legacy
Fantasy
5.95
2001-03-10
In post-apocalypse England, the mysterious 
      agent known only as Oberon helps to create a new life 
      for the inhabitants of London. Sequel to Maeve 
      Ascendant.

Вот мой старый код

import xml.etree.ElementTree as ET
tree = ET.parse('xmlfile.xml')
root = tree.getroot()
a = input('Enter Tag Name : ')
for x in root.findall(a):
    item =x.attrib.get('id')
    print(item)
    for y in x:
        print(y.text)

Вывод:

Enter Tag Name : rock
bk102
Ralls, Kim
Midnight Rain
Fantasy
5.95
2000-12-16
A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.

Приведенный выше код напечатает атрибут id значение и все данные имени тега, которые вы вводите с помощью ввода (в do c у второго дочернего элемента есть рок-тег, вы можете ссылаться на документ)

Необязательный код, но важно при обработке атрибутов тега и дочернего тега данные:

Этот код, который печатает все атрибуты введенного имени тега

import xml.etree.ElementTree as ET
tree = ET.parse('xmlfile.xml')
root = tree.getroot()
a = input('Enter Tag Name : ')
for x in root.findall(a):
    item =x.attrib
    print(item)

Вывод:

Enter Tag Name : rock
{'id': 'bk102'}

Этот код будет печатать выбранный атрибут имени тега задается как пользовательский ввод

import xml.etree.ElementTree as ET
tree = ET.parse('xmlfile.xml')
root = tree.getroot()
a = input(''Enter Tag Name')
for x in root.findall(a):
    item =x.attrib.get('id')
    print(item)

вывод:

Enter Tag Name : rock
bk102

Этот код будет обрабатывать отдельных детей независимо от того, какого ребенка вы хотите. В моем случае я только что получил доступ только к автору и описанию рок-тега.

import xml.etree.ElementTree as ET
tree = ET.parse('xmlfile.xml')
root = tree.getroot()
a = input('Enter Tag Name : ')
for x in root.findall(a):
    author =x.find('author').text
    description = x.find('description').text
    print('author = ',author)
    print('description = ',description)

Вывод:

Enter Tag Name : rock
author =  Ralls, Kim
description =  A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.
0 голосов
/ 03 апреля 2020

Попробуйте использовать f-строки для вставки переменной:

for y in root[21].find(f'.//div[@ID="{segment_id}"]//input')
...