gpt4 book ai didi

java - 使用 xpath 获取没有兄弟节点的节点以及父节点

转载 作者:行者123 更新时间:2023-12-02 03:00:51 25 4
gpt4 key购买 nike

示例 XML:

<animals>
<cat>cat</cat>
<dog>dog</dog>
<lion>lion</lion>
</animals>

假设如果我搜索元素“dog”,预期结果是
<animals>
<dog>dog</dog>
<animals>

我只想要父节点(动物)和搜索节点(狗)。不应显示 sibling (猫,狮子)。我如何通过 XPath 实现此目的?

最佳答案

简单的答案是:不能,因为 XPath 选择节点并且不会改变 DOM。

您可以通过 xslt 转换来完成此操作。

例如,您可以发出所有节点,但会通过仅允许里面有一只猫的节点并删除所有其他动物来过滤动物节点:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" ></xsl:output>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="//animals[cat]">
<xsl:comment>CAT animals</xsl:comment>
<animals>
<xsl:apply-templates select="cat"/>
</animals>
</xsl:template>

<xsl:template match="//animals[not(cat)]">
<xsl:comment>Skipped</xsl:comment>
</xsl:template>



<xsl:template match="cat">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>

如果你想改变当前的 dom 元素,你可以简单地选择所有不需要的节点并删除它们。

    XPath xpath = XPathFactory.newInstance().newXPath();

NodeList unitAnimals = (NodeList) xpath.evaluate("//animals[cat]/*[not(self::cat)]", doc, XPathConstants.NODESET);
for(int i = 0; i<unitAnimals.getLength();i++){
Node unitAnimal = unitAnimals.item(i);
Node parentNode = unitAnimal.getParentNode();
parentNode.removeChild(unitAnimal);
}

关于java - 使用 xpath 获取没有兄弟节点的节点以及父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42385818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com