4

たとえば、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>

declaration基本的に、出力 xml ファイルでとsystemと 残りをシリアルにマージしたいと考えています。JAVAを使用してこれを行う方法は?長文すみません!!!

4

3 に答える 3

6

他の利用可能な XML 処理 API と比較して、DOMBuilderJDOMSAXBuilder 使用すると、次の点で優れています。

  • XML ドキュメントの変更
  • XML ツリーのトラバースと任意のセクションへのランダム アクセス
  • ドキュメントのマージ

これは、2 つの 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 
于 2013-10-11T12:05:10.587 に答える