How to Get Values of All Elements from Xml String in Java

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

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();

How to retrieve element value of XML using Java?

If your XML is a String, Then you can do the following:

String xml = ""; //Populated XML String....

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();

If your XML is in a file, then Document document will be instantiated like this:

Document document = builder.parse(new File("file.xml"));

The document.getDocumentElement() returns you the node that is the document element of the document (in your case <config>).

Once you have a rootElement, you can access the element's attribute (by calling rootElement.getAttribute() method), etc. For more methods on java's org.w3c.dom.Element

More info on java DocumentBuilder & DocumentBuilderFactory. Bear in mind, the example provided creates a XML DOM tree so if you have a huge XML data, the tree can be huge.

  • Related question.

Update Here's an example to get "value" of element <requestqueue>

protected String getString(String tagName, Element element) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();

if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}

return null;
}

You can effectively call it as,

String requestQueueName = getString("requestqueue", element);

read and get xml values in java

Assuming you want the one that has a name of "application"..

You can also simplify your code, there is no need to check the type of the Nodes, getElementsByTagName will only ever return nodes of type Element.

Example

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<event id=\"370e7324-3-85ec-63dac16aacb6\">\n"
+ "<properties>\n" + "<property enc=\"BASE64\" name=\"state\" value=\"Hrthyw35WmnmewqzRlYXI=\"/>\n"
+ "<property enc=\"BASE64\" name=\"record\" value=\"mjhm65WmnmewqzRlYXI=\"/>\n"
+ "<property enc=\"BASE64\" name=\"application\" value=\"Q2FsZWmnmewqzRlYXI=\"/>\n" + "</properties>\n"
+ "</event>\n";

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(xml)));
doc.getDocumentElement().normalize();
NodeList properties = doc.getElementsByTagName("property");

for (int index = 0; index < properties.getLength(); index++) {
Node node = properties.item(index);
Element element = (Element) node;
if ("application".equals(element.getAttribute("name"))) {
String name = element.getAttribute("name");
String valueEncoded = element.getAttribute("value");
String decoded = new String(Base64.getDecoder().decode(valueEncoded));
System.out.println("--value--" + decoded);
}
}

As an alternative to writing your own filtering logic, you can express this with XPath, a XML selection language with native Java support.

XPath xPath = XPathFactory.newInstance().newXPath();
Element element = (Element) xPath.compile("//property[@name=\"application\"]").evaluate(doc, XPathConstants.NODE);
String value = element.getAttribute("value");

Extract all the recurring element of XML using java

You got all id's but you are only looking at first item with .item(id).

Method getElementsByTageName("ID") returns you NodeList so you can got trough all ids for example like that:

File xmlFile = new File("src/main/resources/example.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document element = dBuilder.parse(xmlFile);

NodeList list = element.getElementsByTagName("ID");
for (int i = 0; i < list.getLength(); i++){
Node specificIDNode = list.item(i);
System.out.println(specificIDNode.getTextContent());
}

Extract values from xml file using Java

Though I dont suggest the below approach to use Regex to get element values, but if you are too desperate to get then try the below code:

public class xmlValue {
public static void main(String[] args) {
String xml = "<ns2:aResponse xmlns:ns2=\"http://www.***.com/F1/F2/F3/2011-09-11\">\n" +
" <createBEntityResponse bEntityID=\"328\" />\n" +
"</ns2:aResponse>";
System.out.println(getTagValue(xml,"createBEntityResponse bEntityID"));
}
public static String getTagValue(String xml, String tagName){
String [] s;
s = xml.split("createBEntityResponse bEntityID");
String [] valuesBetweenQuotes = s[1].split("\"");
return valuesBetweenQuotes[1];
}
}

Output: 328

Note: Better solution is to use XML parsers

This will fetch the first tag value:


public static String getTagValue(String xml, String tagName){
return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}

Other way around is to use JSoup:

Document doc = Jsoup.parse(xml, "", Parser.xmlParser()); //parse the whole xml doc
for (Element e : doc.select("tagName")) {
System.out.println(e); //select the specific tag and prints
}

How to extract list of values in an XML node using Java

for get attribute's values

String name = secondExtendedDataElementNode.getAttributes().getNamedItem("name").getNodeValue();
String type = secondExtendedDataElementNode.getAttributes().getNamedItem("type").getNodeValue();

firstly get the comma-separated values into the Array

String[] commaSeparatedValue = secondExtendedDataElementNode.selectSingleNode("values").getText().split(",");

then add these values into the List,

with java8

valuesList = Arrays.stream(commaSeparatedValue).collect(Collectors.toList());

with java9

valuesList = List.of(commaSeparatedValue);


Related Topics



Leave a reply



Submit