【问题标题】:python xml minidom get the full content of childnode that contains both child and textpython xml minidom 获取包含子节点和文本的子节点的全部内容
【发布时间】:2016-08-18 23:19:01
【问题描述】:

我正在寻找使用 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)的全部内容?

【问题讨论】:

    标签: python xml python-3.x xml-parsing minidom


    【解决方案1】:

    遍历子节点并在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 库更直接、更易于使用和理解的东西。例如,看看在xml mode 中使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多