xml python解析获取父节点名称:minidom

时间:2012-05-08 13:25:07

标签: python xml

我怎么知道父节点的名字说我在label =“shirt”,我怎么知道它的父节点是john_carter,其父节点是“FG”。是否有可能知道(在minidom中)

                          -90                  。         。         

        <Object type="Layer" id="6" label="FG" expanded="True">
            <Properties>
                <Property id="blur" constant="True">
                    <Value>0</Value>
                </Property>
                .
                .
                .


                <Property id="objects" expanded="True" constant="True">
                    <Object type="Layer" id="7" label="john_carter">
                        <Properties>
                            <Property id="blur" constant="True">
                                <Value>0</Value>
                            </Property>
                            .
                            .
                            .


                            <Property id="objects" expanded="True" constant="True">
                                <Object type="Layer" id="8" label="shirt" selected="True">
                                    <Properties>
                                        <Property id="blur" constant="True">
                                            <Value>0</Value>
                                        </Property>
                                        .
                                        .
                                        .
                            .
                            .
                            .
                .
                .
                .


    .
    .
    .

1 个答案:

答案 0 :(得分:1)

也许是这样的?

import xml.dom.minidom

def getParentObjectNode(node):
    while node.parentNode:
        node = node.parentNode
        if node.nodeName == "Object":
            return node

xml = xml.dom.minidom.parse("C:\\myxml.xml")
for shirtNode in xml.getElementsByTagName("Object"):
    if shirtNode.getAttribute("label") == "shirt":
        break

shirtParentObject = getParentObjectNode(shirtNode)
print(shirtParentObject.getAttribute("label"))
shirtParentParentObject = getParentObjectNode(shirtParentObject)
print(shirtParentParentObject.getAttribute("label"))