In this post we will demonstrate how can we use JDOM to parse XML. To understand it better i am not taking a symetric xml where you have same set of tags. we will use maven to get the required jar.
Add below dependency to your pom to get the jdom jar
<dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.5</version> </dependency>Lets take an example XML as below.
<Response>
<Header>
<Text> data 1</Text>
</Header>
<BODY>
<CODE>1234</ERR-CODE>
<MSG-DATA>
<TEXT-DATA>Awesome Message</TEXT-DATA>
</MSG-DATA>
</BODY>
<BODY>
<CODE>4567</ERR-CODE>
</BODY>
</Response>
Now, Suppose you need to read ERR-CODE and TEXT-DATA. JDOM provide easy access of each element in XML. java code as belowpackage com.varun.test;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
/**
* Below code will parse and XML and read specific element using Jdom library
*
* @author
*
*/
public class JDOMParser {
public static void main(String[] args) throws JDOMException, IOException {
// Creates a new JAXP-based SAXBuilder
SAXBuilder saxBuilder = new SAXBuilder();
// reads xml from file
File file = new File("E:\\javaTechnologyHelper\\Test.xml");
// create Document object of the file
Document document = (Document) saxBuilder.build(file);
// read the root element
Element rootElement = document.getRootElement();
System.out.println("Root Element :: " + rootElement.getName());
// Under that root element , get the list of all the children with name
// as "BODY"
List<Element> listElement = rootElement.getChildren("BODY");
// iterate through the list: in our case we will have only one object in list
for (Element node : listElement) {
// we can directly access the value of child elements of this node
System.out.println("Value of CODE :: "+ node.getChildText("CODE"));
// Since TEXT-DATA is child of the child element of BODY, we will get the
// child of BODY and then again get the child of that
Element el = node.getChild("MSG-DATA");
if (el != null)
System.out.println("Value of TEXT-DATA :: "+ el.getChildText("TEXT-DATA"));
}
}
}
Response after execution :
Root Element :: Response Value of CODE :: 1234 Value of TEXT-DATA :: Awesome Message Value of CODE :: 4567
No comments:
Post a Comment