0

我正在使用 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>
4

1 回答 1

2

您必须参考XML DOM 文档并咬紧牙关。

要获取第一个<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)
于 2013-03-28T11:07:25.777 回答