1

我试图找到一种在使用 minidom 解析 xml 文件时获取索引号的方法。xml 看起来像这样

<stuff>
    <morestuff>
        <sometag>catagory1</sometag>
        <path pathversion="1">/path Im looking to for</path> #<--info i'm after
        <path pathversion="2">/path I don't need</path>
        <path pathversion="3">/path I don't need</path>
    </morestuff>
    <morestuff>
        <sometag>catagory2</sometag>
        <path pathversion="1">/other path I'm looking for</path> #<--info i'm after
        <path pathversion="2">/path I don't need</path>
        <path pathversion="3">/path I don't need</path>
    </morestuff>
</stuff>

我想做这样的事情

for element in node.getElementsByTagName('sometag'):
    if element.firstChild.data == 'catagory1':
        elementid = element.indexnumber #<----how do I write the [0], or [1] to a variable so I can use it to discribe the position in the next line
        var1 = node.getElementsByTagName('path')[elementid].firstChild.data
    if element.firstChild.data == 'catagory2':
        elementid = element.indexnumber
        var2 = node.getElementsByTagName('path')[elementid].firstChild.data
4

2 回答 2

0

像 Keith 建议的那样使用 etree 怎么样:-

['/path Im looking to for', "/other path I'm looking for"]

使用此代码:-

import xml.etree.ElementTree as ET
tree = ET.fromstring('''<stuff>
    <morestuff>
        <sometag>catagory1</sometag>
        <path pathversion="1">/path Im looking to for</path>
        <path pathversion="2">/path I don't need</path>
        <path pathversion="3">/path I don't need</path>
    </morestuff>
    <morestuff>
        <sometag>catagory2</sometag>
        <path pathversion="1">/other path I'm looking for</path>
        <path pathversion="2">/path I don't need</path>
        <path pathversion="3">/path I don't need</path>
    </morestuff>
</stuff>
''')
print [e.text for e in tree.findall('.//morestuff/path[@pathversion="1"]')]
于 2013-03-01T11:07:45.663 回答
0

这将创建一个包含您想要的信息的字典:

import xml.dom.minidom
doc = xml.dom.minidom.parseString(test)

paths = {}

for element in doc.getElementsByTagName('morestuff'):
    # get the text value of the sometag tag
    category = element.getElementsByTagName('sometag')[0].firstChild.nodeValue

    # get all the paths which are children of the morestuff element
    for path in element.getElementsByTagName('path'):
        if path.getAttribute('pathversion') == '1':
            pathstr = path.firstChild.nodeValue
            paths[category] = pathstr

print paths

我得到的输出是:

{u'catagory1': u'/path Im looking to for', u'catagory2': u"/other path I'm looking for"}
于 2013-03-01T10:42:03.453 回答