【问题标题】:Seems xpath translate not working as expected in java8似乎 xpath translate 在 java8 中无法按预期工作
【发布时间】:2020-05-31 20:48:04
【问题描述】:

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

例子-

实际-

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 在任何情况下都只返回输出。

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

 <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 的任何情况,我现在想要项目值

【问题讨论】:

    标签: java xpath case-insensitive


    【解决方案1】:

    您的代码工作正常,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>
    

    您的代码将同时匹配带有 code="RemoveCatalogVersionJob" 和 code="RemoveCatalogVersionJob1" 的 itemtype。

    【讨论】:

      猜你喜欢
      • 2019-11-27
      • 2023-03-05
      • 1970-01-01
      • 2020-09-15
      • 2016-01-24
      • 1970-01-01
      • 2022-12-17
      • 2021-06-07
      • 2013-02-10
      相关资源
      最近更新 更多