Python minidom xml解析以获取第一个子节点的值

时间:2013-03-28 10:45:22

标签: python xml minidom

我正在使用python minidom来解析xml,但是无法让它在xml以下工作。我想选择第一个服务器标签并想要name标签的值,在本例中为“Server1”

<class>
<name>MyClass</name>
<security>
<name>MyClass</name>
</security>
<server>
<name>Server1</name>
<ssl>
 <name>Server1</name>
</ssl>
<server-info>
 <name>Server1</name>
</server-info>
</server>
<server>
<name>Server2</name>
<ssl>
 <name>Server2</name>
</ssl>
<server-info>
 <name>Server2</name>
</server-info>
</server>
<server>
<name>Server3</name>
<ssl>
 <name>Server3</name>
</ssl>
<server-info>
 <name>Server3</name>
</server-info>
</server>
</class>

1 个答案:

答案 0 :(得分:2)

你必须参考XML DOM documentation并咬紧牙关。

要获取第一个<server>元素,然后是<name>

from xml.dom import minidom

document = minidom.parse(inputfilename)

def findChildNodeByName(parent, name):
    for node in parent.childNodes:
        if node.nodeType == node.ELEMENT_NODE and node.localName == name:
            return node
    return None

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

# Get the first of all `<server>` nodes
server = document.getElementsByTagName('server')[0]

# Get the first child node that is a `<name>` element
name = findChildNodeByName(server, 'name')
if name is not None:
    print getText(name.childNodes)