Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I get the value of specific nodes in Java from XML.

I have structure like what you see bellow and I want to get the values of userFileds(2,N.A. for the first one and 1 for the last one(it is part of real xml data. the number of elements are more):

<element class="AufOrgKombination" hash="AOK_1414931143186_52">
<field name="layer">4</field><field name="name">Function </field>
<field name="description">des</field>
<userField hash="USERFIELD_1415779871581_0">2.0</userField>
<userField hash="USERFIELD_1415386348389_3">N.A.</userField>
</element>
<element class="AufOrgKombination" hash="AOK_1414931143186_23">
<field name="layer">4</field><field name="name">Function 2 </field>
<field name="description">des</field>
<userField hash="USERFIELD_1415779871581_0">1</userField>
</element>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
366 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should consider not to use the XPath API, but a library that handles it for you (Disclosure: I'm affiliated with that project). You probably want to reflect the XML structure somehow to your object structure. There are some difficulties to overcome (Namespaces, default namespaces, type conversion, mapping to Java objects, ...). One possible solution using the suggested library:

public class Demo {

public interface Projection {
    interface Element {
        @XBRead("./userField")
        List<String> getUserFieldValues();
    }

    @XBRead("//element")
    List<Projection.Element> getElements();
}

public static void main(final String[] args) throws IOException {
    Projection projection = new XBProjector().io().url("resource://data.xml").read(Projection.class);
    for (Projection.Element element : projection.getElements()) {
        for (String userField : element.getUserFieldValues()) {
            System.out.println(userField);
            }
        }
    }
}

This program prints out:

2.0
N.A.
1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...