Guest User

Java XML Parser Example

a guest
Dec 24th, 2011
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. // ReadXMLFile.java
  2. import javax.xml.parsers.DocumentBuilderFactory;
  3. import javax.xml.parsers.DocumentBuilder;
  4. import org.w3c.dom.Document;
  5. import org.w3c.dom.NodeList;
  6. import org.w3c.dom.Node;
  7. import org.w3c.dom.Element;
  8. import java.io.File;
  9.  
  10.  
  11. public class ReadXMLFile {
  12.  
  13.     public static void main(String argv[]) {
  14.  
  15.       try {
  16.  
  17.           for (String s: argv) {
  18.               System.out.println(s);
  19.           }
  20.  
  21.         File fXmlFile = new File(argv[0]);
  22.         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  23.         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  24.         Document doc = dBuilder.parse(fXmlFile);
  25.         doc.getDocumentElement().normalize();
  26.  
  27.         System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
  28.         NodeList nList = doc.getElementsByTagName("staff");
  29.         System.out.println("-----------------------");
  30.  
  31.         for (int temp = 0; temp < nList.getLength(); temp++) {
  32.  
  33.            Node nNode = nList.item(temp);
  34.            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
  35.  
  36.               Element eElement = (Element) nNode;
  37.  
  38.               System.out.println("First Name : " + getTagValue("firstname", eElement));
  39.               System.out.println("Last Name : " + getTagValue("lastname", eElement));
  40.                   System.out.println("Nick Name : " + getTagValue("nickname", eElement));
  41.               System.out.println("Salary : " + getTagValue("salary", eElement));
  42.  
  43.            }
  44.         }
  45.       } catch (Exception e) {
  46.         e.printStackTrace();
  47.       }
  48.   }
  49.  
  50.   private static String getTagValue(String sTag, Element eElement) {
  51.     NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
  52.  
  53.         Node nValue = (Node) nlList.item(0);
  54.  
  55.     return nValue.getNodeValue();
  56.   }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment