我进行了很多搜索以找到完全相同的内容,但找不到。这里的问题是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在任何情况下都只返回输出。

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

 <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的任何情况,我都需要项目值

最佳答案

您的代码可以正常工作,并且XPath可以正确评估。问题在于XPath表达式的末尾包含“ ancestor :: itemtype”,并且两个匹配的“ attribute”元素都只有一个祖先,名称为“ 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>


您的代码将匹配代码为=“ =” RemoveCatalogVersionJob“的两个项目类型和代码=” RemoveCatalogVersionJob1“。

07-24 18:30