简体   繁体   中英

A better way to do XML in Java

There are a lot of questions that ask the best XML parser, I am more interested in what is the XML parser that is the most like Groovy for Java?

I want:

SomeApiDefinedObject o = parseXml( xml );
for( SomeApiDefinedObject it : o.getChildren() ) {
   System.out.println( it.getAttributes() );
}

The most important things are that I don't want to create a class for every type of XML node, I'd rather just deal with them all as strings, and that building the XML doesn't require any converters or anything, just a simple object that is already defined

If you have used the Groovy XML parser, you will know what I'm talking about

Alternatively, would it be better for me to just use Groovy from Java?

Here is something quick you can do with Sun Java Streaming XML Parser

    FileInputStream xmlStream = new FileInputStream(new File("myxml.xml"));
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(xmlStream);
    while(reader.hasNext()){
        reader.next();
        for(int i=0; i < reader.getAttributeCount(); i++) {
           System.out.println(reader.getAttributeName(i) + "=" + reader.getAttributeValue(i));
        }
    }

I would like to shamelessly plug the small open-source library I have written to make parsing XML in Java a breeze.

Check out Jinq2XML.

http://code.google.com/p/jinq2xml/

Some sample code would look like:

Jocument joc = Jocument.load(urlOrStreamOrFileName);
joc.single("root").children().each(new Action() {
    public void act(Jode j){
        System.out.println(j.name() + ": " + j.value());
    }
});

Looks like all you want is a simple DOM API, such as provided by dom4j . There actually already a DOM API in the Standard Library (the org.w3c.dom packages), but it's only the API, so you need a separate implementation - might as well use something a little more advanced like dom4j.

Use Groovy.

It seems that your primary goal is to be able to access the DOM in a "natural" way via object accessors, and Java won't let you do this without defining classes. Groovy, because it is "duck typed," will allow you to do this.

The only reason not to use Groovy is if (1) XML processing is a very small part of your application, and/or (2) you have to work with other people who may want to program strictly in Java.

Whatever you do, do not decide to "just deal with them all as strings." XML is not a simple format, and unless you know the spec inside and out, you're not likely to get it right. Which means that your XML will be rejected by spec-conformant parsers.

I highly recommend JAXB . Great for XML <--> Java objects framework.

There used to be a very small and simple XML parser called NanoXML. It seems not to be developed anymore, but it's still available at http://devkix.com/nanoxml.php

I have good experiences with XStream . It's fairly quick and will serialize and deserialize Java to/from XML with no schema and very little code It Just Works™. The Java object hierarchies it builds will directly mirror your XML.

我使用Dozer和Castor来获取OTOM(对象到对象映射)。

Try This code!!!!!

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.*;
import javax.xml.*;

import java.io.File;
import java.io.IOException;


public class XmlDemo {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
       {
//        Get Document Builder
//      Get Document Builder
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          DocumentBuilder builder = factory.newDocumentBuilder();

          //Build Document
          Document document = builder.parse(new File("D:/test.xml"));

          //Normalize the XML Structure; It's just too important !!
          document.getDocumentElement().normalize();

          //Here comes the root node
          Element root = document.getDocumentElement();
          System.out.println(root.getNodeName());

          //Get all employees
          NodeList nList = document.getElementsByTagName("company");
          System.out.println(nList.getLength());

          System.out.println("============================");

          visitChildNodes(nList);
       }

       //This function is called recursively
       private static void visitChildNodes(NodeList nList)

       {
           Node tempNode = null;

//         System.out.println("The Number of child nodes are " + (nList.getLength()) );

           if(!(nList.getLength() == 1)) {
//             System.out.println("The Number of child nodes are " + (nList.getLength()) );

//             for (int temp = 0; temp < nList.getLength(); temp++)
//                {
//                   Node node = nList.item(temp);
//                   if (node.getNodeType() == Node.ELEMENT_NODE)
//                   {
//                     System.out.println();
//                      System.out.println("Node Name = " + node.getNodeName() + ";");
//                   }
//                }   
           }

          for (int temp = 0; temp < nList.getLength(); temp++)
          {
             Node node = nList.item(temp);
             if (node.getNodeType() == Node.ELEMENT_NODE)
             {
               System.out.println();
                System.out.println("Node Name = " + node.getNodeName() + ";");

//              if (node.hasAttributes()) {
//                     // get attributes names and values
//                     NamedNodeMap nodeMap = node.getAttributes();
//                     for (int i = 0; i < nodeMap.getLength(); i++)
//                     {
//                         tempNode = nodeMap.item(i);
//                         System.out.println("                     Attr  : " + tempNode.getNodeName()+ "; Value = " + tempNode.getNodeValue());
//                     }
//                     
//                 }else {
////                       System.out.println("No Attributes");
//                 }

                if (node.hasChildNodes()) {
                       NodeList nodeList = node.getChildNodes();

                       if((node.getChildNodes().getLength()/2)>0) {
                           System.out.println("This node has child nodes "+ (node.getChildNodes().getLength()/2));
                       System.out.println("Child nodes of : [ " + node.getNodeName() + " ] =>");
                       for(int k = 0;k < nodeList.getLength(); k++) {

                           Node n = nodeList.item(k);
                           if (n.getNodeType() == Node.ELEMENT_NODE)
                         {


                               if((k<(nodeList.getLength()))) {
                                   System.out.println("                           [ " + n.getNodeName() + " ] =>" );
                                   if (n.hasAttributes()) {
//                                     // get attributes names and values
                                       NamedNodeMap nodeMap = n.getAttributes();
                                       for (int i = 0; i < nodeMap.getLength(); i++)
                                       {
                                           tempNode = nodeMap.item(i);
                                           System.out.println("                                  Attr  : " + tempNode.getNodeName()+ "; Value = " + tempNode.getNodeValue() + " ]");
                                       }

                                   }else {
//                                     System.out.println("No Attributes");
                                   }



                               }else if((k==(nodeList.getLength()))) {
                                   System.out.println("                     [ " + n.getNodeName() + " ]");

                               }


                       }
                       }

                       System.out.println("                  ]");
                       }
                      visitChildNodes(node.getChildNodes());


                   }

        }
          }
       }

}

    enter code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM