解析包含嵌套标签的xml

时间:2011-12-09 20:10:30

标签: java xml

的xml:

<Node name="1">
   <Node name="2">
       <Node name="4"></Node>
   </Node>
   <Node name = "3">
       <Node name="5"></Node>
    </Node>
</Node>

我想在java中创建以下对象

Node{
 String name;
 List<Node> nodeList
}

是否有任何xml解析库可以执行此操作。 我尝试过xstream和简单,但还是没能弄明白。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

此代码使用XStream并生成您要查找的输出。

节点类:

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

@XStreamAlias("Node")
public class Node {
    @XStreamAsAttribute
    private String name;

    @XStreamImplicit
    private List<Node> nodes = new ArrayList<Node>();

    public Node(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Node> getNodes() {
        return nodes;
    }

    public void setNodes(List<Node> nodes) {
        this.nodes = nodes;
    }

    public void addNode(Node n) {
        nodes.add(n);
    }
}

主要课程:

import com.thoughtworks.xstream.XStream;


public class NodeXStream {

    public static void main(String[] args) {
        Node n1 = new Node("1");
        Node n2 = new Node("2");
        Node n3 = new Node("3");
        Node n4 = new Node("4");
        Node n5 = new Node("5");

        n1.addNode(n2);
        n1.addNode(n3);

        n2.addNode(n4);
        n3.addNode(n5);


        XStream xs = new XStream();
        xs.processAnnotations(Node.class);

        // To XML
        String myXML = xs.toXML(n1);

        // From XML
        Node newNode = (Node) xs.fromXML(myXML);

    }

}

编辑: 添加了反序列化代码。

要反序列化,您还需要将XPP3库添加到构建路径。它是XStream的一部分。

答案 1 :(得分:0)

public class DigestNodes {
    List<Node> nodes;

    public DigestNodes() {
        nodes= new ArrayList<Node>();
    }

    public static void main(String[] args) {
        DigestNodes digestStudents = new DigestNodes();
        digestStudents.digest();
    }

    private void digest() {
        try {
            Digester digester = new Digester();

            digester.push(this);

            digester.addObjectCreate("*/node", Node.class );

            digester.addSetProperties( "*/node");

            digester.addSetNext( "*/node", "addNode" );

            DigestNodes ds = (DigestNodes) digester.parse(this.getClass()
                                .getClassLoader()
                                .getResourceAsStream("node.xml"));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void addNode( Node node ) {
        nodes.add(node);
    }
}