到目前为止,我正在从事一个项目,他一直依赖于设置: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')]在切换到XSLT2.0时,我切换到了Saxon转换器。撒克逊是一个更精确的变压器(好在海事组织)。它认识到这些xpath表达式是“错误的”,现在我必须修复像上面这样的一组xpath表达式才能工作,而不管所引用的名称空间前缀是什么(客户端可以选择在URI http://tastyTreats.com/giftbasket前加上我所知道的'fluffybunnies‘)。
我还收到了其他一些很好的建议,here关于如何利用local-name()功能来实现我所需要的大部分东西。我的xpath现在读到:
/*[local-name()='GiftBasket']/*[local-name()='Fruit']/*[local-name()='Apple'][Color='Red'][contains(TasteDescription,'sweet')]但是,这仍然不准确,因为谓词中引用的元素仍然引用确切的元素名称Color和TasteDescription,而不具有名称空间的灵活性。是否有更好的方法为所有在味道描述中包含“甜”的红苹果编写xpath,同时保持名称空间前缀的灵活性?
发布于 2016-08-22 15:01:23
正如您提到的XSLT2.0,在XSLT2.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')]应该可以很好地使用名称空间http://tastyTreats.com/giftbasket来选择输入文档中的元素。
如果您在Saxon 9中使用JAXP XPath API,那么请参阅https://saxonica.plan.io/boards/3/topics/1649关于如何使用该API设置这样一个默认命名空间:
((XPathEvaluator)xpath).getStaticContext().setDefaultElementNamespace("http://tastyTreats.com/giftbasket");https://stackoverflow.com/questions/39082567
复制相似问题