[英]Reading XML file using xml.dom.minidom or elementtree - Python
我的XML文件具有以下形式:
<user name="John Doe" title="Manager">
This manager is responsible for...
<group title="USA">
<column name="Inventory">
Inventory of the products
</column>
<column name="Sells">
Sells of the products
</column>
</group>
</user>
而且用戶和列可以連續進行,每個用戶可以有許多列。 我正在嘗試使用ET或DOM來讀取列名和行之間的描述。 使用ET,我能夠讀取所有標簽,但不能讀取標簽之間的內容。 例如,我看不懂“產品銷售”
我敢肯定這很簡單,但是對於Python和整個XML主題來說我是新手。 我只能使用python 2.7。 我的代碼如下:
我的代碼看起來像這樣(它仍在處理中,尚未完成):
with open(file.xml, 'rt') as f:
tree = ET.parse(f)
for node in tree.iter():
if node.tag == 'column':
print node
我沒有您的代碼,所以看不到您在做什么,但是tag.text
應該為您提供標簽的文本。 例:
import xml.etree.ElementTree as ET
xml = '''<user name="John Doe" title="Manager">
<group title="USA">
<column name="Inventory">
Inventory of the products
</column>
<column name="Sells">
Sells of the products
</column>
</group>
</user>'''
root = ET.fromstring(xml)
inventory = root.findall('.//column[@name="Inventory"]')
print inventory[0].text.strip()
sells = root.findall('.//column[@name="Sells"]')
print sells[0].text.strip()
最終,我設法弄清了整個代碼,它對我有用。
for node in tree.iter():
if node.tag == 'user':
userName = node.attrib['name']
#print userName
for group in node.getchildren():
if group.tag == 'group':
groupName = group.attrib['title']
#print groupName
for column in group.getchildren():
if column.tag == 'column':
columnName = column.attrib['name']
columnDesc = column.text
#print columnName, column.text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.