Piyush Vinchurkar

17
reputation
7

package test;

import java.io.File;

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

import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList;

public class ReadXML {

public static void main(String argv[]) {

  try {
    File fXmlFile = new File("D:\\Header.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    //FileWriter fstream = new FileWriter("D:\\XMLFlat.txt");
   // BufferedWriter out = new BufferedWriter(fstream);

    NodeList nList = doc.getElementsByTagName("B4K");
    System.out.println("-----------------------");
    StringBuffer str = new StringBuffer();
    for (int temp = 0; temp < nList.getLength(); temp++) {

       Node nNode = nList.item(temp);

       if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;
          str.append("B4K");
          String b4k01 = getTagValue("B4K01", eElement);
          System.out.println(b4k01);
          //String b4k01field = addSpace(b4k01,Consts.B4K01);
         // str.append(b4k01field);

          String b4k02 = getTagValue("B4K02", eElement);
          System.out.println(b4k02);

         // String b4k02field = addSpace(b4k02,Consts.B4K02);
          //str.append(b4k02field);

          String b4k03 = getTagValue("B4K03", eElement);
          System.out.println(b4k03);
          //String b4k03field = addSpace(b4k03,Consts.B4K03);
          //str.append(b4k03field);

       }
     //  out.write(str.toString());
     //  out.close();
    }

  } catch (Exception e) {
    e.printStackTrace();
  }

}

private static String getTagValue(String sTag, Element eElement) { try { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

    Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
} catch (Exception e) {
    // TODO: handle exception
    System.out.println("Below Tag is not present:");
}
return sTag;

}

}