我有一个非常大的嵌套 XML 文件(下面是一个极简示例),我试图了解所有父节点和子节点是什么。
目前,我将此xml文件加载到python中的beautifulsoup并单独读取每个节点。我看到的问题是我不知道有多少父节点以及它们是什么。
找到父节点集和相应子节点的最快方法是什么?
<AppTestData>
<Contact>
<Name>
<First name> foo</First name>
<last name> bar</last name>
</Name>
<Age>33</Age>
<City>York</City>
...
</Contact>
<Agent>
<Code>A103S</Code>
<Region>North</North>
<Resp>Service</Resp>
....
</Agent>
<Product>
<Cat>Electronics</Cat>
...
</Product>
</AppTestData>
希望输出:
AppTestData -> Contact -> [Name, age, city]
AppTestData -> Contact -> Name ->[first name, last name]
AppTestData -> Agent -> [Code, Region, Resp]
试试这个。我已经修改了您的 XML 中的错误。
from simplified_scrapy import utils, SimplifiedDoc
xml = '''
<AppTestData>
<Contact>
<Name>
<First_name> foo</First_name>
<last_name> bar</last_name>
</Name>
<Age>33</Age>
<City>York</City>
...
</Contact>
<Agent>
<Code>A103S</Code>
<Region>North</Region>
<Resp>Service</Resp>
....
</Agent>
<Product>
<Cat>Electronics</Cat>
...
</Product>
</AppTestData>
'''
def printTag(lst, parent):
if len(lst)==1:
parent.append(lst[0].tag)
print (parent)
return
flag = False
for ele in lst:
children = ele.children
if not children:
flag = True
else:
p = parent[:]
p.append(ele.tag)
printTag(children,p)
if flag:
parent.append(lst.tag)
print (parent)
# xml = utils.getFileContent('data.xml')
doc = SimplifiedDoc(xml)
root = doc.child
children = root.children
printTag(children,[root.tag])
结果:
['AppTestData', 'Contact', 'Name', ['First_name', 'last_name']]
['AppTestData', 'Contact', ['Name', 'Age', 'City']]
['AppTestData', 'Agent', ['Code', 'Region', 'Resp']]
['AppTestData', 'Product', 'Cat']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句