How to Retrieve Element Value of Xml Using Java

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

java Get value from xml tag

Getting the node value of an element will return null (as documented here).

Instead you need to either get the element's text content (since Java 5):

doc.getElementsByTagName("Id").item(0).getTextContent();

Or, if you're stuck in Java 1.4 or older, you can access the element's text node and get the text node's value:

doc.getElementsByTagName("Id").item(0).getFirstChild().getNodeValue();

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

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 get the specific entire tag values from XML using JAVA

Hello try this function by replacing

System.out.println(element.getTextContent());

with

System.out.println(description(element, ""));

public String description(Node n, String tab){
String str = new String();
if(n instanceof Element){
Element element = (Element)n;
str += "<" + n.getNodeName();
if(n.getAttributes() != null && n.getAttributes().getLength() > 0){
NamedNodeMap att = n.getAttributes();
int nbAtt = att.getLength();
for(int j = 0; j < nbAtt; j++){
Node noeud = att.item(j);
str += " " + noeud.getNodeName() + "=\"" + noeud.getNodeValue() + "\" ";
}
}
str += ">";
if(n.getTextContent()!= null ){
str += "<![CDATA[" + n.getTextContent().replace("\n", "").trim()+ "]]";
}
if(n.getChildNodes().getLength() == 1)
str += n.getTextContent();
int nbChild = n.getChildNodes().getLength();
NodeList list = n.getChildNodes();
String tab2 = tab + "\t";
for(int i = 0; i < nbChild; i++){
Node n2 = list.item(i);
if (n2 instanceof Element){

str += "\n " + tab2 + description(n2, tab2);
}
}
if(n.getChildNodes().getLength() < 2)
str += "</" + n.getNodeName() + ">";
else
str += "\n" + tab +"</" + n.getNodeName() + ">";
}
return str;
}

How to retrieve element value from SOAP response using Java?

I have tried like below,

public static Document loadXMLString(String response) throws Exception
{
DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(response));

return db.parse(is);
}

public static List<String> getFullNameFromXml(String response, String tagName) throws Exception {
Document xmlDoc = loadXMLString(response);
NodeList nodeList = xmlDoc.getElementsByTagName(tagName);
List<String> ids = new ArrayList<String>(nodeList.getLength());
for(int i=0;i<nodeList.getLength(); i++) {
Node x = nodeList.item(i);
ids.add(x.getFirstChild().getNodeValue());
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
return ids;
}

From above code, you will get ids list. After that, you can put those into the String Array and return those into String array like below,

List<String> output = getFullNameFromXml(response, "fullName");
String[] strarray = new String[output.size()];
output.toArray(strarray);
System.out.print("Response Array is "+Arrays.toString(strarray));

how to get the attribute value of an xml node using java

Since your question is more generic so try to implement it with XML Parsers available in Java .If you need it in specific to parsers, update your code here what you have tried yet

<?xml version="1.0" encoding="UTF-8"?>
<ep>
<source type="xml">TEST</source>
<source type="text"></source>
</ep>
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("uri to xmlfile");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//ep/source[@type]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nl.getLength(); i++)
{
Node currentItem = nl.item(i);
String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();
System.out.println(key);
}

how to get specific element's value from a large XML

public Map<String, Integer> countElements(File xmlFile) {

Map<String, Integer> counts = new HashMap<>();

try {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
FileInputStream fileInputStream = new FileInputStream(xmlFile);
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileInputStream);

while(reader.hasNext()) {
reader.next();
if(reader.isStartElement() && reader.getLocalName().equals("SynsetRelation")) {
String relTypeValue = reader.getAttributeValue("", "relType");

if(!counts.containsKey(relTypeValue)) {
counts.put(relTypeValue, 0);
}

counts.put(relTypeValue, counts.get(relTypeValue) + 1);
}
}

fileInputStream.close();
} catch (XMLStreamException | IOException e) {
e.printStackTrace();
}

return counts;
}

This code uses a Stream reader, meaning it will only load one element at a time in memory. This makes it efficient, even for large files.

A map is used to keep track of the counts. Every time I encounter a "SynsetRelation" element I check first to see if it is already counted, then I increment the counter.

The result is map containing the counts per detected value.

You would use it like this in your main class:

public class Main {
public static void main(String[] args) {
Map<String, Integer> results = countElements(new File("your file location here.xml"));
}
}


Related Topics



Leave a reply



Submit