代码之家  ›  专栏  ›  技术社区  ›  user366312

为什么会这样dom.firstChild.firstChild文件.nodeValue是否打印根标记内的文本?

  •  0
  • user366312  · 技术社区  · 5 年前

    <?xml version="1.0" encoding="utf-8"?>
    <library>library-text. :D
        <book isbn="1111111111">
            <title lang="en">T1 T1 T1 T1 T1</title>
            <date>2001</date>
            <author>A1 A1 A1 A1 A1</author>     
            <price>10.00</price>
        </book>
        <book isbn="2222222222">
            <title lang="en">T2 T2 T2 T2 T2</title>
            <date>2002</date>
            <author>A2 A2 A2 A2 A2</author>     
            <price>20.00</price>
        </book>
        <book isbn="3333333333">
            <title lang="en">T3 T3 T3 T3</title>
            <date>2003</date>
            <author>A3 A3 A3 A3 A3y</author>        
            <price>30.00</price>
        </book>
    </library>
    

    import xml.dom.minidom as minidom
    
    xml_fname = "library.xml"
    
    dom = minidom.parse(xml_fname) 
    
    print(dom.firstChild.tagName)
    print(dom.firstChild.firstChild.nodeValue)
    

    输出

    library
    library-text. :D
    

    为什么会这样 dom.firstChild.firstChild.nodeValue 打印根标记内的文本?

    dom.firstChild.nodeValue

    1 回复  |  直到 5 年前
        1
  •  2
  •   Martijn Pieters    5 年前

    DOM中的节点不仅表示元素,文本值也是 <library> 'library-text. :D\n ' :

    >>> dom.firstChild.firstChild
    <DOM Text node "'library-te'...">
    >>> dom.firstChild.firstChild.nodeValue
    'library-text. :D\n    '
    

    nodeValue 财产 Element s是 总是 空(== None 在Python中);请参见 DOM level 1 definition for Node

    nodeType (例如。, 节点值 对于一个 attributes Comment ),此返回 null .

    什么节点类型包含什么类型的值 Node.nodeValue 在中指定 Definition Group NodeType section .

    domapi是一个非常有用的工具 裸骨,基本 minidom 支架)。如果你能避免的话,你通常根本不想使用它。在Python中,使用更高级的API,如 ElementTree API (使用 lxml library ,这是一个功能更丰富的兼容实现)。

    使用ElementTree,您主要处理 元素,文本可通过 text tail 元素的属性。