Header Ad

Showing posts with label XML Parsing. Show all posts
Showing posts with label XML Parsing. Show all posts

Tuesday, June 15, 2010

Parsing XML string or content using java code

The following program is an example for parsing the XML string using code.

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XMLParse {
  public static void main(String arg[]) throws Exception{
    String xmlRecords = "A"
        "";

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("employee");

    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Elementnodes.item(i);

      NodeList name = element.getElementsByTagName("name");
      Element line = (Elementname.item(0);
      System.out.println("Name: " + getCharacterDataFromElement(line));

      NodeList title = element.getElementsByTagName("title");
      line = (Elementtitle.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }

  }

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterDatachild;
      return cd.getData();
    }
    return "";
  }
}

Friday, August 17, 2007

Reading XML from another Site using Java code

import="com.sun.org.apache.xerces.internal.util.URI"
import="java.io.InputStream"
import="java.net.URL"
import="javax.xml.parsers.DocumentBuilderFactory"
import="javax.xml.parsers.DocumentBuilder"
import="org.w3c.dom.Document"
import="org.w3c.dom.NodeList"
import="org.w3c.dom.NamedNodeMap"
import="org.w3c.dom.Node"

URL url= new URL("www.google.com");
InputStream in=url.openStream();
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(in);

If you want to get retrive entire node list that can be done by

NodeList nodeList=document.getElementsByTagName("NameofTheNode");

By these all the node will come in that Node List.
If you want to retrive the attributes with in that Node,that can be done by

Node node= nodeList.item(indx);
NamedNodeMap nnm=node.getAttributes();
String href=nnm.getNamedItem("AttributeNamewithinthatNode").getNodeValue();