Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 243
Patan Avatar asked Jan 04 '13 14:01

Patan


3 Answers

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();
like image 165
vault Avatar answered Oct 19 '22 03:10

vault


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())
like image 39
Grooveek Avatar answered Oct 19 '22 02:10

Grooveek


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);
like image 7
McDowell Avatar answered Oct 19 '22 03:10

McDowell