I am new to XML. I want to read the following XML on the basis of request name. Please help me on how to read the below XML in Java -
<?xml version="1.0"?> <config> <Request name="ValidateEmailRequest"> <requestqueue>emailrequest</requestqueue> <responsequeue>emailresponse</responsequeue> </Request> <Request name="CleanEmail"> <requestqueue>Cleanrequest</requestqueue> <responsequeue>Cleanresponse</responsequeue> </Request> </config>
Get root node: Document class provides the getDocumentElement() method to get the root node and the element of the XML file. Get all nodes: The getElementByTagName() method retrieves all the specific tag name from the XML file.
In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.
Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it.
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.
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);
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