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

双斜杠(//)作为XML注释

  •  2
  • navidof  · 技术社区  · 7 年前

    我有点惊讶,使用双斜杠作为注释似乎是有效的XML。

    xml.etree.ElementTree xmllint --format :

    <root>
        <child1>text1</child1>
        <child2></child2> //this is a valid comment
        <child3></child3>
    </root>
    

    我最初认为这可以被视为根元素的文本节点,但在python3上尝试证明我错了:

    >>> import xml.etree.ElementTree as ET
    >>> r=ET.parse("test.xml").getroot()
    >>> r.text
    '\n    '
    >>> child2=r[1]
    >>> child2.text
    >>> ET.tostring(child2)
    b'<child2 /> //this is a valid comment\n    ' 
    

    3 回复  |  直到 7 年前
        1
  •  6
  •   kjhughes    7 年前

    comments <!-- comment --> 在XML中。你看到了 //this is a valid comment mixed content .你也可以很容易地忽略 // .

    ET.tostring(e) 正在返回 e.tail (后面出现的文字 e )作为其字符串表示的一部分 e ET.tostring(e) e 并且不包括其文本节点同级。但是,自从 e、 尾部

        2
  •  2
  •   zx485 potemkin    7 年前

    这不是有效的注释,而是 <root> 要素

    <child2></child2> //this is a valid comment
    

    …元素节点(“child2”)、文本节点(“//这是有效的注释”)、元素节点(“child3”)。。。

    你想要的是

    <child2></child2> <!-- this is a valid comment -->
    

    真实的

    …元素节点(“child2”)、注释节点(“//这是有效注释”)、元素节点(“child3”)。。。

    (为了简单起见,我省略了空文本节点。)

        3
  •  0
  •   james31rock    7 年前
    <!--This is a valid comment-->