如何使用现有属性创建新的XML DOC?

时间:2014-03-13 11:00:10

标签: java xml xml-parsing

我有一个XML文档,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<model>
    <id>_1</id>
    <nodes>
    <id>_2</id>
    <stencil>TASK</stencil>
    </nodes>
    <nodes>
    <id>_3</id>
    <stencil>TASK</stencil>
    </nodes>
</model>

我必须使用第一个doc中的节点属性创建另一个xml doc。对于新文档,我必须创建父节点 叫做#34;定义&#34;。而不是&#34;模型&#34;第一个文档中的节点我必须创建一个&#34;进程&#34;新文档中的节点有一个 属性&#34; id&#34;哪个值与&#34; id&#34;的内容相同?模型的子节点。对于每个节点&#34;第一个doc中的节点 如果他们的&#34;模板&#34;子节点内容等于&#34; TASK&#34;我创建了一个&#34;任务&#34;新xml文档中的节点。

<?xml version="1.0" encoding="UTF-8"?>
<definitions>
  <process id="_1">
    <task id="_2">
    </task>
    <task id="_3">
    </task>
  </process>
</definitions> 

为实现这一目标,我创建了三个类:定义,过程和任务:

public class Definitions {
         public Process extractProcess(Document simpleXml_doc) throws XPathExpressionException{
            Process p = new Process();
            p.setProcess("process");
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression xPathEx1 = xPath.compile("/model/id");
            Node n1 = (Node) xPathEx1.evaluate(simpleXml_doc, XPathConstants.NODE);
            p.setIdProcess(n1.getTextContent());
            return p;
        }
}

public class Process {

     private String process;
     public String getProcess(){
         return process;
     }
     public void setProcess(String process){
         this.process = process;
     }
         private String idProcess;
            public String getIdProcess(){
                return idProcess;
            }
            public void setIdProcess(String idProcess){
                this.idProcess = idProcess;
            }


    public ArrayList<Task> extractTasks(Document firstXml_doc) throws XPathExpressionException{
        ArrayList<Task> taskList = new ArrayList<>();
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathEx1 = xPath.compile("/model/nodes/stencil");
        NodeList nl1 = (NodeList) xPathEx1.evaluate(simpleXml_doc, XPathConstants.NODESET);
        for(int index=0; index<nl1.getLength(); index++){
            if(nl1.item(index).getTextContent().equals("TASK")){
                Task t = new Task();
                t.setTask("task");
                XPathExpression xPathEx2 = xPath.compile("/model/nodes/id");
                NodeList nl2 = (NodeList) xPathEx2.evaluate(simpleXml_doc, XPathConstants.NODESET);
                t.setIdTask("_" + nl2.item(index).getTextContent());
                taskList.add(t);
            }
        }
        return taskList;
    }
}

public class Task {
    private String task; 
    public String getTask(){
        return task;
    }
    public void setTask(String task){
        this.task = task;
    }
    //do krijoj properties per atributet e elementit task
    private String idTask;
    private String nameTask;
    public String getIdTask(){
        return idTask;
    }
    public void setIdTask(String idTask){
        this.idTask = idTask;
    }
}

我只是想知道这是否是定义各个类的正确方法。 任何人都可以告诉我使用此方法创建和填充新文档的节点 班? 我使用DOM解析器,我知道如何创建节点和填充属性值, 但我总是在一个班级完成这项工作,而不是使用不同的班级 元素。

1 个答案:

答案 0 :(得分:1)

我认为你在这里有正确的想法,但也许你可能想考虑使用JAXB。它更清洁,更容易理解。使用JAXB,您将给定的输入XML文件解组为Java对象。然后,您创建新的Java对象并将其封送回XML字符串/文件。

这里是如何...

我们假设您有以下内容: -

INPUT XML STRUCTURE

这是您拥有的XML结构,并将其放在文件中。

<强> input.xml中

<?xml version="1.0" encoding="UTF-8"?>
<model>
    <id>_1</id>
    <nodes>
        <id>_2</id>
        <stencil>TASK</stencil>
    </nodes>
    <nodes>
        <id>_3</id>
        <stencil>TASK</stencil>
    </nodes>
</model>

为输入XML创建JAVA对象

模型类

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement
public class Model {
    @XmlElement
    private String id;

    @XmlElement
    private List<Node> nodes;

    public Model() {
    }

    public Model(String id, List<Node> nodes) {
        this.id = id;
        this.nodes = nodes;
    }

    public String getId() {
        return id;
    }

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

节点类

import javax.xml.bind.annotation.XmlElement;

public class Node {

    @XmlElement
    private String id;

    @XmlElement
    private String stencil;

    public Node() {
    }

    public Node(String id, String stencil) {
        this.id = id;
        this.stencil = stencil;
    }

    public String getId() {
        return id;
    }

    public String getStencil() {
        return stencil;
    }
}

为OUTPUT XML创建JAVA对象

定义类

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Definitions {

    @XmlElement
    private Process process;

    public Definitions() {
    }

    public Definitions(Process process) {
        this.process = process;
    }

    public Process getProcess() {
        return process;
    }
}

流程类

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import java.util.List;

public class Process {

    @XmlAttribute
    private String id;

    @XmlElement
    private List<Task> task;

    public Process() {
    }

    public Process(String id, List<Task> task) {
        this.id = id;
        this.task = task;
    }

    public String getId() {
        return id;
    }

    public List<Task> getTask() {
        return task;
    }
}

任务类

import javax.xml.bind.annotation.XmlAttribute;

public class Task {

    @XmlAttribute
    private String id;

    public Task() {
    }

    public Task(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}

读取和编写XML

主要类

public class Main {
    public static void main(String[] args) throws JAXBException {

        // initialize JAXB
        JAXBContext context = JAXBContext.newInstance(Model.class, Definitions.class);

        // Unmarshal input XML into Java object
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Model model = (Model) unmarshaller.unmarshal(Main.class.getClassLoader().getResourceAsStream("input.xml"));

        // Map old Java object to new Java object
        List<Task> tasks = new ArrayList<Task>();
        for (Node node : model.getNodes()) {
            tasks.add(new Task(node.getId()));
        }

        // Marshal new Java object into XML
        Definitions definitions = new Definitions(new Process(model.getId(), tasks));

        StringWriter sw = new StringWriter();

        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.marshal(definitions, sw);

        System.out.println(sw.toString());
    }
}

<强>结果

执行上面的代码时,您将获得以下XML字符串: -

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<definitions>
    <process id="_1">
        <task id="_2"/>
        <task id="_3"/>
    </process>
</definitions>