XML Parsing in Java

Posted by on Jun 25, 2012 in Blog, Technical | 0 comments

Parsing a xml file can be done easily by following the below explained Steps:

  1. Xml parsing using jdom
  2. Download “jdom-1.0.jar”
  3. Right click on “project”->Bulid Path-> Configure build path->Libraries ->Add External jar -> select “jdom-1.0.jar”. JDOM : JDOM is used for parsing, creating, manipulating, and serialising XML documents, it is a tree based Java api. JDOM represents an XML document as a tree composed of elements, attributes, comments, processing instructions, text nodes. SAXBuilder : SAXBuilder is class that builds a JDOM Document from file,stream,reader etc.
  4. Create a SAXBuilder object which is used to Build a JDOM document from files. SAXBuilder builder = new SAXBuilder(); File xml = new File(“sample.xml”); Document document = builder.build(xml);
    In JDOM, most navigation takes place through the methods of the Element class
  5. getRootElement() method is used to get root element of sample.xml file. Element rootElement = document.getRootElement();
  6. The child elements of each Element are available in a “list”, returned by the getChildren() method List rootChild = rootNode.getChildren();
    getChild() method is used to get single child element. rootElement.getChild(“first”);// specify name of a child element
  7. A List containing Attribute objects, one for each of the element’s attributes.The list is accessible through the getAttributes(). List attributeList = childElement.getAttributes();
  8. getName() method is used to get attribute name and getValue() method is used to get attribute value. Iterator iterator = attributeList.iterator(); while (iterator.hasNext()) { Attribute attribute = (Attribute) iterator.next(); String name = attribute.getName(); String value = attribute.getValue();

Leave a Reply

Your email address will not be published. Required fields are marked *