Vous êtes sur la page 1sur 5

DomParsing.java import java.util.ArrayList; import java.util.List; import javax.xml.parsers.*; import org.w3c.dom.

*; public class DomParsing { private static final String FILE_NAME_STRING = "hello.xml"; public static void main(String args[]) { List childlist = new ArrayList(); try { // load and parse the document DocumentBuilder builder; // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use the factory to create a builder builder = factory.newDocumentBuilder(); Document document = builder.parse(FILE_NAME_STRING); // retrieve and display the root node Element node = document.getDocumentElement(); recurseThroughDoc(node); } catch (Exception e) { e.printStackTrace(); } } private static void recurseThroughDoc(Node node) { System.out.println("Name: " + node.getNodeName()); System.out.println("Value: \"" + node.getNodeValue() + "\""); int type = node.getNodeType(); if (type == Node.ELEMENT_NODE) { System.out.println("Type: Element Node"); } else if (type == Node.TEXT_NODE) { System.out.println("Type: Text Node"); } else {

System.out.println("Type: Other, type number: " + type); } NodeList nodeList = node.getChildNodes(); System.out.println("child count: " + nodeList.getLength()); System.out.println(); if (nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { recurseThroughDoc(nodeList.item(i)); } } } }

INPUT FILE: hello.xml <?xml version="1.0"?> <Employee-Detail><Employee> <Emp_Id>E-001</Emp_Id> <Emp_Name>Vinod</Emp_Name> <Emp_E-mail>Vinod1@yahoo.com</Emp_E-mail> </Employee></Employee-Detail>

SAXParserCheck.java import org.xml.sax.*; import org.xml.sax.helpers.*; import java.io.*; public class SAXParserCheck{ public static void main(String[ ] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter XML file name:"); String xmlFile = bf.readLine(); SAXParserCheck par = new SAXParserCheck(xmlFile); }

public SAXParserCheck(String str){ try{ File file = new File(str); if (file.exists()){ XMLReader reader = XMLReaderFactory.createXMLReader(); reader.parse(str); System.out.println(str + " is well-formed!"); } else{ System.out.println("File not found: " + str); } } catch (SAXException sax){ System.out.println(str + " isn't well-formed"); } catch (IOException io){ System.out.println(io.getMessage()); } } }

INPUT FILE: hello.xml <?xml version="1.0"?> <Employee-Detail><Employee> <Emp_Id>E-001</Emp_Id> <Emp_Name>Vinod</Emp_Name> <Emp_E-mail>Vinod1@yahoo.com</Emp_E-mail> </Employee></Employee-Detail

Vous aimerez peut-être aussi