XPath表达式忽略带有引用子元素的谓词的名称空间

时间:2016-08-22 14:47:50

标签: xpath xml-namespaces

我正在开发一个迄今为止依赖于设置的项目: DocumentBuilderFactory.setNamespaceAware(false); 实现名称空间灵活的xpath(忽略可传入的任何前缀)。

这只能在过去使用,因为正在使用xalan转换器,虽然从技术上讲,将名称空间设置为false的行为应该是最好的,对于给定的xml,xalan将以下xpath视为有效。

的xml:

<t:GiftBasket xmlns:t="http://tastyTreats.com/giftbasket">
    <t:Fruit>
        <t:Apple>
            <t:Name>Cameo</t:Name>
            <t:Color>Red</t:Color>
            <t:TasteDescription>Juicy, crisp, and sweet with just a touch of tart, the Cameo is thought to come from both the Red and the Yellow Delicious.</t:TasteDescription>
        </t:Apple>
        <t:Apple>
            <t:Name>Empire</t:Name>
            <t:Color>Red</t:Color>
            <t:TasteDescription>The interior is crisp and creamy white while being firmer than the McIntosh, so it makes for a good cooking apple. </t:TasteDescription>
        </t:Apple>
        <t:Apple>
            <t:Name>Granny Smith</t:Name>
            <t:Color>Green</t:Color>
            <t:TasteDescription>Hard feel, crisp bite, and extremely tart taste. Some prefer to cook it, which sweetens it up.</t:TasteDescription>
        </t:Apple>
    </t:Fruit>
    <t:Candy>
        <t:Chocolate>Dark</t:Chocolate>
    </t:Candy>
</t:GiftBasket>

的xpath:

/GiftBasket/Fruit/Apple[Color='Red'][contains(TasteDescription,'sweet')]

切换到xslt 2.0时,我切换到了Saxon-HE变压器。撒克逊是一个更精确的变压器(IMO的好东西)。它认识到这些xpath表达式是“错误的”,我现在必须修复一堆像上面这样的xpath表达式,无论引用的名称空间前缀如何(客户端可以选择将URI http://tastyTreats.com/giftbasket作为'fluffybunnies'作为所有人的前缀我知道)

我收到了关于如何利用local-name()功能来实现我所需要的大部分内容的其他好律师here。我的xpath现在写着:

/*[local-name()='GiftBasket']/*[local-name()='Fruit']/*[local-name()='Apple'][Color='Red'][contains(TasteDescription,'sweet')]

但是,这仍然不准确,因为谓词中引用的元素仍然引用了精确的元素名称ColorTasteDescription而没有名称空间灵活性。是否有更好的方法为所有在其口味描述中包含'sweet'的红苹果编写xpath,同时保持名称空间前缀的灵活性?

1 个答案:

答案 0 :(得分:1)

当您提到XSLT 2.0时,您可以在XSLT 2.0中定义

<xsl:stylesheet xpath-default-namespace="http://tastyTreats.com/giftbasket" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

然后使用没有前缀名称的XPath表达式和XSLT匹配模式来选择该特定命名空间中的元素,也就是说,路径/GiftBasket/Fruit/Apple[Color='Red'][contains(TasteDescription,'sweet')]应该可以正常工作,以使用命名空间{{1}选择输入文档中的元素}}

如果您将JAXP XPath API与Saxon 9一起使用,请参阅https://saxonica.plan.io/boards/3/topics/1649,了解如何使用该API设置此类默认命名空间:

http://tastyTreats.com/giftbasket
相关问题