繁体   English   中英

使用JAVA合并多个XML文件的不同节点

[英]Merging different nodes of multiple XML files using JAVA

我在arrayList中有一些xml文件,例如A.xml B.xml ,我希望合并一些节点,而其余节点保持原样使用java。 我是新手,所以我不知道该怎么做。

一个xml:

<?xml version="1.0" encoding="UTF-8"?>
<nta>
<declaration>
    bool A, B;
    bool C;
</declaration>
<template>
    <location id="1"  x="10" y="10"/>
    <transition>
        <source ref="3"/>
    </transition>    
</template>
<system> system AND;</system>
</nta>

B.XML:

<?xml version="1.0" encoding="UTF-8"?>
<nta>
<declaration>
    int f,k;
    bool D;
</declaration>
<template>
    <location id="100"  x="40" y="89"/>
    <transition>
        <source col="9"/>
    </transition>    
</template>
<system> system OR;</system>
</nta>

并输出:

<?xml version="1.0" encoding="UTF-8"?>
<nta>
<declaration>
    bool A, B;
    bool C;
    int f,k;
    bool D;
</declaration>
<template>
    <location id="1"  x="10" y="10"/>
    <transition>
        <source ref="3"/>
    </transition>    
</template>
<template>
    <location id="100"  x="40" y="89"/>
    <transition>
        <source col="9"/>
    </transition>    
</template>
<system> system AND, OR;</system>
</nta>

基本上我想合并declarationsystem ,其余的是在输出xml文件中串行。 如何使用JAVA做到这一点? 对不起,长篇大论!!!

与其他可用的XML处理API相比,对我来说,拥有DOMBuilderSAXBuilder JDOM更适合:

  • 修改XML文档
  • XML树遍历和随机访问任何部分
  • 合并文件

这是合并两个XML文档的完整工作示例:

    SAXBuilder builder = new SAXBuilder();
    Document doc1 = builder.build(new File("E:\\XML1.xml"));
    Document doc2 = builder.build(new File("E:\\XML2.xml"));

    String rootName = doc1.getRootElement().getName();
    Element newRoot = new Element(rootName);
    Document newDoc = new Document(newRoot);

    Element root1 = doc1.getRootElement();
    Element root2 = doc2.getRootElement();

         // creating declaraion element by merging the declaration content
    Element declaration = new Element("declaration");
    declaration.addContent(root1.getChildText("declaration"));
    declaration.addContent(root2.getChildText("declaration"));
    newRoot.addContent(declaration); // add declaration element to new document

         newRoot.addContent(root1.getChild("template").clone()); 
                       // directly adding template from document XML1, 
                      //after getting template child,
                     //it needs to be cloned to detached  from its parent  

     newRoot.addContent(root2.getChild("template").clone()); 
                       // same for document XML2

     /*** now code yourself  for system element here ***/

    XMLOutputter outputter = new XMLOutputter();
    outputter.output(newDoc, System.out); 
                  // output the new doc, pass your OutputStream to this function 

您可以使用诸如dom之类的xml解析器来读取所需的部分(声明和系统),然后聚合它们以获得所需的输出。

您将获得大量有关在java中读取编写 xml的示例。

在这里或以任何其他方式解析XML,然后从这里使用javax.xml.parsers.DocumentBuilder来做你想要的。创建一个新的XML文档。

暂无
暂无

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

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