Wednesday, 29 August 2012

java Parsing string xml


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 test {

  public static void main(String arg[]) throws Exception{
     
String xmlRecords = "Drop ur xml here ";

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

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

    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);
      Element ele = (Element) nodes.item(0);  
      System.out.println("lccp: " + getCharacterDataFromElement(ele));
      String lccp = ele.getAttribute("lccp_trnno");
      String lccp_srccode = ele.getAttribute("lccp_srccode");
      String lccp_dstncode = ele.getAttribute("lccp_dstncode");
      System.out.println("lccp: " + lccp);
    }
  }

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

  
   

No comments:

Post a Comment