简体   繁体   中英

How to get values of all elements from XML string in Java?

I have the a string in XML format. I want to read it and get the values of the elements.

I have tried Java JAXBContext unmarshell , but this needs creation of class which is not necessary for me.

String:

<customer>
    <age>35</age>
    <name>aaa</name>
</customer>

I want to get the values of age and name .

This is your xml:

String xml = "<customer><age>35</age><name>aaa</name></customer>";

And this is the parser:

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(xml));

Document doc = builder.parse(src);
String age = doc.getElementsByTagName("age").item(0).getTextContent();
String name = doc.getElementsByTagName("name").item(0).getTextContent();

JSoup has a nice support for XML

import org.jsoup.*     
import org.jsoup.nodes.*   
import  org.jsoup.parser.*

//str is the xml string 
String str = "<customer><age>35</age><name>aaa</name></customer>"
Document doc = Jsoup.parse(str, "", Parser.xmlParser());
System.out.println(doc.select("age").text())

Using XPath in the standard API:

String xml = "<customer>" + "<age>35</age>" + "<name>aaa</name>"
    + "</customer>";
InputSource source = new InputSource(new StringReader(xml));
XPath xpath = XPathFactory.newInstance()
                          .newXPath();
Object customer = xpath.evaluate("/customer", source, XPathConstants.NODE);
String age = xpath.evaluate("age", customer);
String name = xpath.evaluate("name", customer);
System.out.println(age + " " + name);

JDOM is quite easy to use:

SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("c:\\file.xml");
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();
List list = rootNode.getChildren("customer");

for (int i = 0; i < list.size(); i++) {

    Element node = (Element) list.get(i);

    System.out.println("Age : " + node.getChildText("age"));
    System.out.println("Name : " + node.getChildText("name"));         
}

Just as a tidbit for users with more COMPLICATED XMLs, as I do. If you have elements with the same name but, different attributes, for example:

<field tag="8"> Country </field>
<field tag="12"> State </field>

The way to extract them is to follow @vault's answer but, make sure to change the value in the .item(int) function.

If you want the first field you use .item(0) . If you want the second you use .item(1)

Hope this helps for future users as it did for me.

I iterate over all elements with this generic method:

public static void getElementValues(Node node) {
    NodeList nodeList = node.getChildNodes();
    for (int i = 0, len = nodeList.getLength(); i < len; i++) {
        Node currentNode = nodeList.item(i);
        if (len == 1 && currentNode.getNodeType() == Node.TEXT_NODE) {
            System.out.println(node.getLocalName() + "=" + currentNode.getTextContent());
        }
        else if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            getElementValues(currentNode);
        }
    }
}

Result:

age = 35
name = aaa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM