使用 xml.dom.minidom 或 elementtree - Python 读取 XML 文件

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,我能够读取所有标签,但不能读取标签之间的内容。例如,我无法阅读 "Sells of the products"

我相信这很简单,但我是 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