python xml minidom 获取包含子节点和文本的子节点的全部内容

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

我可以得到 text1text2 但不能 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 库更直接、更易于使用和理解的东西。例如,看看使用 BeautifulSoup in an xml mode:

是多么容易
>>> 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