简体   繁体   English

Python XML:获取直接子节点

[英]Python XML: get direct child nodes

I have a xml like below. 我有一个像下面的xml。 I want to get all direct child nodes under Node1. 我想获得Node1下的所有直接子节点。 I am trying to use childNodes, however, it return Node21 and Node22 also. 我试图使用childNodes,但它也返回Node21和Node22。 How can I just get those direct chirld nodes 我怎样才能获得那些直接的chirld节点

<Node1>
  <Node11>
    <Node21>
    </Node21>
    <Node22>
    </Node22>
    <Node23>
    </Node23>
  </Node11>
  <Node12>
  </Node12>
  <Node13>
  </Node13>
</Node1>

UPDATE Sorry for the confusion. 更新很抱歉混乱。 I made a mistake, it seems it only get the direct child nodes. 我犯了一个错误,似乎只能得到直接的子节点。 However, the item number is the childnodes still exceeds the real child nodes. 但是,项目编号是子节点仍然超过真实的子节点。 I try to get the nodeName. 我尝试获取nodeName。 I get a lot of "#text" 我得到了很多“#text”

xml.ElementTree.Element supports the iterator protocol, so you can use list(elem) as follows: xml.ElementTree.Element支持迭代器协议,因此您可以使用list(elem) ,如下所示:

import xml.etree.cElementTree as ET

s = '''
<Node1>
  <Node11>
    <Node21>
    </Node21>
    <Node22>
    </Node22>
    <Node23>
    </Node23>
  </Node11>
  <Node12>
  </Node12>
  <Node13>
  </Node13>
</Node1>
'''

root = ET.fromstring(s)

print root
print list(root)

There are two ways you can go about handling the text nodes. 有两种方法可以处理文本节点。 If you really want to keep using dom, you can get rid of the text nodes with a filter: 如果你真的想继续使用dom,你可以用过滤器删除文本节点:

>>> filter(lambda node: node.nodeType != xml.dom.Node.TEXT_NODE, myNode.childNodes)
[<DOM Element: Node11 at 0x18e64d0>, <DOM Element: Node12 at 0x18e6950>, <DOM Element: Node13 at 0x18e6a70>]

or a list comprehension: 或列表理解:

>>> [x for x in myNode.childNodes if x.nodeType != xml.dom.Node.TEXT_NODE]
[<DOM Element: Node11 at 0x18e64d0>, <DOM Element: Node12 at 0x18e6950>, <DOM Element: Node13 at 0x18e6a70>]

If you don't need to keep using dom, I would suggest using ElementTree as Eli Bendersky suggested. 如果您不需要继续使用dom,我建议使用ElementTree,如Eli Bendersky建议的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM