【问题标题】:XPath get first child comment only before any other elementsXPath 仅在任何其他元素之前获取第一个子注释
【发布时间】:2021-06-09 20:34:54
【问题描述】:

使用 XPath,我想在任何其他子元素之前获取那些是 item 元素的第一个子元素的 cmets。

我有这样的 XML:

<list>
    ...
    <item id="52">
        <!-- this is optional comment, need get this -->
        <randomParam>asd</randomParam> <!-- not this comment -->
        <anotherRandomParam type="3" />
        <paramText /> <!-- not this comment -->
        ...
    </item>
    <item id="53">
        <param1>test</param1> <!-- not need this comment -->
        <param2 title="text">text</param2>
        <someParam>
        <!-- not need this comment -->
                <test />
                <test /> 
                <test />
        </someParam>
        ...
    </item>
    ...
</list>

【问题讨论】:

    标签: xml dom xpath


    【解决方案1】:

    这个 XPath,

    //item/comment()[not(preceding-sibling::*)]
    

    将选择 item 元素的所有 comment() 子元素,它们之前没有元素兄弟,

    <!-- this is optional comment, need get this -->
    

    根据要求。

    【讨论】:

    • 我在网上尝试XPath并得到TypeError: Cannot read property 'childPosition' of undefined,element()不是xpath函数?
    • 我冒昧地猜测您在xpather.com 上得到了该结果,即known to fail to implement the XPath standard faithfully.... ...已确认。避免使用 xpather.com——它不符合 XPath 标准。如果您使用兼容的 XPath 站点或库,您会发现上述 XPath 运行良好。
    • 是的,但是在 PHP(使用 libxml)中我收到警告:DOMXPath::query(): Invalid expression [...][...],我认为需要将element() 替换为*,或者node() 也可以在选项@987654332 下使用@
    • @PlayerKillerYKT:element() 需要 XPath 2.0,而 libxml 仅支持 XPath 1.0。是的,您可以使用*,这样上述 XPath 将适用于 XPath 1.0 及更高版本。答案已更新。这仍然不能免除 xpather.com 的问题,它仍然以 * 失败。
    • Сan你回答请,如果在其他元素之前可能有几个 cmets,我怎么能得到多个?像这样:&lt;item&gt;&lt;!-- comment get this --&gt;&lt;!-- other comment and get this --&gt;&lt;param&gt;test&lt;/param&gt;&lt;param2 /&gt;&lt;/item&gt;.
    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2021-06-21
    • 2020-04-26
    • 2015-12-04
    • 2016-09-02
    • 2019-05-21
    相关资源
    最近更新 更多