xpath for xml to get node information

时间:2016-03-16 11:33:42

标签: java xml xpath

I am writing a java program to search for text and return its node information.

  1. The program should search for text anywhere in the document and.
  2. Return 5 predefined node and node-values.

Sample xml file : -

<project xmlns="https://example.hoom/go/bing">
    <name>purchaseOrder </name>
    <property name="included" type="hidden">true</property>
    <locales>
        <locale>en</locale>
        <locale>hi</locale>
    </locales>
    <defaultLocale>en</defaultLocale>
    <gamespace>
        <name locale="en">hambook</name>
        <name locale="de">hambook</name>
        <lastChanged>2014-03-05T18:47:30</lastChanged>
        <lastChangedBy>userx</lastChangedBy>
        <property name="included" type="hidden">true</property>
        <gamespace>
            <name locale="en">DbBook</name>
            <name locale="zw">DbBook</name>
            <hecrotSubject status="valid">
                <name locale="en">hexValue</name>
                <name locale="zw">hexValue</name>
                <hecrotItem>
                    <name locale="en">hireValue</name>
                    <name locale="zw">hireValue</name>
                    <hello>searchTerm</hello>
                </hecrotItem>
            </hecrotSubject>
        </gamespace>
    </gamespace>
    <gamespace>
        <name locale="en">Names</name>
        <lastChanged>2016-01-12T12:42:46</lastChanged>
        <gamespace>
            <name locale="en">Database Layer</name>
            <name locale="zw">Database Layer</name>
            <hecrotSubject status="valid">
                <name locale="en">qsxyz</name>
                <hecrotItem>
                    <name locale="en">myName</name>
                    <hello>...Hi there..</hello>
                </hecrotItem>
            </hecrotSubject>
        </gamespace>
    </gamespace>
</project>

My current xpath is :-

"//*[local-name()='gamespace']/*[local-name()='hecrotSubject']/*[local-name()='hecrotItem'][contains(., '"& searchTerm &"')]/ancestor-or-self::*/*[local-name()='name' and @locale='en']"

Which is giving only the root tag using xpath.compile().evaluate(). While result I need is

name value of five predefined nodes if they contain the search text (searchTerm in this sample xml).

sample result should be:-

Project - purchaseOrder

gamespace - hambook

gamespace - DbBook

hecrotSubject - hexValue

hecrotItem - hireValue

Edit

I am using following statements in java : -

String expression = Xpath;
Strings vals = xPath.compile(expression).evaluate(xmlDocument);
System.out.println(vals);

1 个答案:

答案 0 :(得分:0)

我不知道你为什么只得到 root标签 但是在你的xpaht中,某些值(节点名称)的情况是错误的。修复hecrotSubject和hecrotItem它应该工作。
但顺便说一句,我不明白为什么你使用本地名称设置正确的名称空间,如下所示:

/b:gamespace/b:hecrotsubject/b:hecrotitem[contains(., 'searchTerm')]/ancestor-or-self::*/b:name[@locale='en']" 

更新doe以更新问题

主要问题是你需要迭代NodeList,这可能是xpath evaluate返回的。

看看例如:How to read XML using XPath in Java