首页 > 解决方案 > 似乎 xpath translate 在 java8 中无法按预期工作

问题描述

我进行了很多搜索以找到确切的等价物,但找不到。这里的问题是 java8-javax.xml.xpath.* 的翻译方法没有给出预期的输出。

例子-

实际的-

XPathExpression xpathitemtype = xpath.compile("//*[@type=\"" + xpathType + "\"]/ancestor::itemtype");
final NodeList itemType = (NodeList) xpathitemtype.evaluate(document, XPathConstants.NODESET);

使用翻译-

XPathExpression xpathitemtype = xpath.compile("//*[translate(@type,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='" + xpathType.toLowerCase() + "']/ancestor::itemtype");
final NodeList itemType = (NodeList) xpathitemtype.evaluate(document, XPathConstants.NODESET);

现在我使用 translate 因为我喜欢在给定的 xml 文档中获取 itemType 而不管大小写-

例如,如果值为- exportMedia 或 ExportMedia 或 EXportMEdia 任何情况下都只返回输出。

现在在上面的两个示例中返回相同的输出似乎 translate 在我的情况下不起作用

 <itemtype code="RemoveCatalogVersionJob">
 <attribute qualifier="catalogVersion" type="CatalogVersion">
                    <persistence type="property"/>
                </attribute>
                <attribute qualifier="removedItems" type="ExportMEdia">
                    <persistence type="property"/>
                </attribute>
                <attribute qualifier="notRemovedItems" type="exportMedia">
                    <persistence type="property"/>
                </attribute>
 </itemtype>

如果是 exportMedia 的任何情况,现在我想要项目值

标签: javaxpathcase-insensitive

解决方案


您的代码工作正常,并且 XPath 被正确评估。问题是 XPath 表达式最后包含“ancestor::itemtype”,并且两个匹配的“属性”元素只有一个名为“itemtype”的祖先。

如果您要更改代码以进行测试...

    XPathExpression xpathItemType = xpath.compile("//*[translate(@type,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='" + xpathType.toLowerCase() + "']/@qualifier");
    final NodeList itemType = (NodeList) xpathItemType.evaluate(document, XPathConstants.NODESET);

    for(int i = 0; i < itemType.getLength(); i ++) {
        System.out.println(itemType.item(i).getNodeValue());
    }

...输出将是

removedItems
notRemovedItems

...显示,“ExportMEdia”和“exportMedia”都与您的表达相匹配。

或者,您可以将输入 XML 更改为类似这样的内容(只是一个示例,不知道实际方案):

<items>
    <itemtype code="RemoveCatalogVersionJob">
        <attribute qualifier="notRemovedItems" type="exportMedia">
            <persistence type="property"/>
        </attribute>
    </itemtype>
    <itemtype code="RemoveCatalogVersionJob1">
        <attribute qualifier="removedItems" type="ExportMEdia">
            <persistence type="property"/>
        </attribute>
    </itemtype>
</items>

您的代码将匹配两个 itemtype 与 code="RemoveCatalogVersionJob" 和 code="RemoveCatalogVersionJob1"。


推荐阅读