[英]python xml minidom get the full content of childnode that contains both child and text
我正在寻找使用 xml minidom 提取 xml 文件的内容,这是示例:
<parent>
<child>
text1
<subchild>text2 </subchild>
text3
</child>
</parent>
以下代码仅提取“text1”:
DOMTree = xml.dom.minidom.parse('file.xml')
document = DOMTree.documentElement
parents = document.getElementsByTagName('parent')
for parent in parents:
child = parents.getElementsByTagName('parent')[0]
print(child.childNodes[0].nodeValue) # shows text1
我可以得到text1和text2但不能得到text3
请问如何获得我的子元素和我的子元素( text1 text2 text3 )的完整内容?
迭代子节点并在Text
对象的情况下获取.data
属性,否则firstChild.nodeValue
:
print([node.data.strip() if isinstance(node, xml.dom.minidom.Text) else node.firstChild.nodeValue
for node in child.childNodes])
打印['text1', 'text2 ', 'text3']
。
不过,我会考虑切换到比minidom
库更直接、更易于使用和理解的minidom
。 例如,看看在xml
模式下使用BeautifulSoup
是多么容易:
>>> from bs4 import BeautifulSoup
>>> data = """
... <parent>
... <child>
... text1
... <subchild>text2 </subchild>
... text3
... </child>
... </parent>
... """
>>> soup = BeautifulSoup(data, "xml")
>>> print(soup.child.get_text())
text1
text2
text3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.