Results 1 to 2 of 2

Thread: XML in Java

  1. #1
    Felissa is offline Member
    Join Date
    Jun 2007
    Rep Power

    Exclamation XML in Java

    I am working with XML file. And I'm complicated with the reading and writing of these files in Java. If somebody has the code, to read and/or to write a XML, to be able to analyze it and to use it, serious of much help.


  2. #2
    Marcus is offline Member
    Join Date
    Jun 2007
    Rep Power

    Default XML in Java

    Hello, what do you want to do? , if it is to parse xml you can work with DOM or SAX being this much more fast since using DOM to parse this load the document in memory and creates an object from, example of DOM:

    Java Code:
    <?xml version="1.0"?>
    Java Code:
    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 XMLReader {
     public static void main(String argv []) {
      try {
      File file = new File("c:\\MyXMLFile.xml" );
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(file);
      System.out.println("Root element " + doc.getDocumentElement ().getNodeName());
      NodeList nodeLst = doc.getElementsByTagName("employee") ;
      System.out.println("Information of all employees") ;
      for (int s = 0 ; s < nodeLst.getLength(); s++) {
        Node fstNode = nodeLst.item(s);
        if (fstNode.getNodeType() == Node.ELEMENT_NODE ) {
          Element fstElmnt = (Element) fstNode;
          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname" );
          Element fstNmElmnt = (Element) fstNmElmntLst.item (0);
          NodeList fstNm = fstNmElmnt.getChildNodes();
          System.out.println("First Name : "  +  ((Node) fstNm.item(0)) .getNodeValue());
          NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname") ;
          Element lstNmElmnt = (Element) lstNmElmntLst.item (0);
          NodeList lstNm = lstNmElmnt.getChildNodes();
          System.out.println("Last Name : " + (( Node) lstNm.item(0)) .getNodeValue());
      } catch (Exception e) {
    if you want to continue investigating there are very interesting things like api of XPATH for java (something like query, so that you do not have to cross xml complete in java)
    The Java XPath API
    also this JDOM Simplify XML programming with JDOM

    and here is the articulate where they speak of how turning from SAX to DOM
    Tip: Converting from SAX


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts