【问题标题】:Using XPath to access comments a flat hierachy使用 XPath 访问注释的平面层次结构
【发布时间】:2010-04-14 09:17:34
【问题描述】:

我有一个给定的 XML 文档(结构无法更改)并且想要获取写入节点上方的 cmets。文档如下所示:

<!--Some comment here-->    
    <attribute name="Title">Book A</attribute>
    <attribute name="Author">
       <value>Joe Doe</value>
       <value>John Miller</value>
    </attribute>
<!--Some comment here-->
    <attribute name="Code">1</attribute>

所以 cmets 是可选的,但是如果有的话,我想获取每个属性上方的注释。 使用/*/comment()[n] 会给我注释n,但是对于n=2 我自然会得到第三个属性的注释,所以属性和cmets 之间没有任何联系有什么想法吗? 谢谢

【问题讨论】:

    标签: xml xpath comments xml-comments


    【解决方案1】:

    如果您想选择后跟 attribute 元素的 cmets,那么这应该可以:

    /*/comment()[following-sibling::*[position()=1 and name()='attribute']]
    

    【讨论】:

    • 太棒了,这正是我想要的。谢谢
    【解决方案2】:

    使用

    //comment()[following-sibling::*[1][self::attribute]]
    

    这比当前选择的答案更紧凑、更精确// 缩写是必要的,因为没有提供格式正确的 XML 文档,并且注释节点的嵌套级别未知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多