简体   繁体   English

在Java中使用XML的更好方法

[英]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? 有很多问题需要最好的XML解析器,我更感兴趣的是什么是最像Groovy for Java的XML解析器?

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 最重要的是我不想为每种类型的XML节点创建一个 ,我宁愿只将它们作为字符串处理,而构建XML不需要任何转换器或任何东西,只需要已经定义的简单对象

If you have used the Groovy XML parser, you will know what I'm talking about 如果您使用过Groovy XML解析器,您将会知道我在说什么

Alternatively, would it be better for me to just use Groovy from Java? 或者,对我来说,从Java使用Groovy会更好吗?

Here is something quick you can do with Sun Java Streaming XML Parser 您可以使用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. 我想无耻地插入我编写的小型开源库,以便在Java中解析XML变得轻而易举。

Check out Jinq2XML. 看看Jinq2XML。

http://code.google.com/p/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 . 看起来你想要的只是一个简单的DOM API,例如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. 实际上标准库( org.w3c.dom包)中已经存在DOM API,但它只是API,所以你需要一个单独的实现 - 不妨使用像dom4j更先进的东西。

Use Groovy. 使用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. 看来你的主要目标是能够通过对象访问器以“自然”的方式访问DOM,而Java不会让你在没有定义类的情况下这样做。 Groovy, because it is "duck typed," will allow you to do this. Groovy,因为它是“鸭子类型”,将允许你这样做。

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. 不使用Groovy的唯一原因是:(1)XML处理是应用程序的一小部分,和/或(2)您必须与可能希望严格使用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. XML不是一种简单的格式,除非你知道里面和外面的规范,否则你不太可能正确。 Which means that your XML will be rejected by spec-conformant parsers. 这意味着您的XML将被符合规范的解析器拒绝。

I highly recommend JAXB . 我强烈推荐JAXB Great for XML <--> Java objects framework. 非常适合XML < - > Java对象框架。

There used to be a very small and simple XML parser called NanoXML. 曾经有一个非常小而简单的XML解析器叫做NanoXML。 It seems not to be developed anymore, but it's still available at http://devkix.com/nanoxml.php 它似乎不再开发,但它仍然可以在http://devkix.com/nanoxml.php上找到

I have good experiences with XStream . 我对XStream有很好的体验。 It's fairly quick and will serialize and deserialize Java to/from XML with no schema and very little code It Just Works™. 它相当快,将序列化和反序列化Java到/从XML没有架构和很少的代码It Just Works™。 The Java object hierarchies it builds will directly mirror your XML. 它构建的Java对象层次结构将直接镜像您的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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