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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With