DOMについて。


DOMでのxml文書の連結(マージ)


   myコード(xmlFileName[0]、xmlFileName[1]のitem要素以下を、ルートのAuctionCategoryLeaf以下に追加している。)
       
   DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   
   Document d1 = DB.parse(xmlFileName[0]);
   
   Document d2 = DB.parse(xmlFileName[1]);
   
   NodeList nodeList=d2.getElementsByTagName("item");
   
   Node CategoryNode=d1.getElementsByTagName("AuctionCategoryLeaf").item(0);
   
   for (int i=0;i<nodeList.getLength();i++) {
   	
    Node addNode = d1.importNode(nodeList.item(i),true);
    
    CategoryNode.appendChild(addNode);
   }

DOMのDocumentを出力したい。

  • J2SE1.4.*の場合、2種類方法がある。以降のバージョンだとDOMLevel3とかいう標準が採用されているようで、他にも色々あったり、速かったりする。
  • javax.xml.transform.Transformerを使用する方法。
       myコード

TransformerFactory factory = TransformerFactory.newInstance();
  	
Transformer transformer0 = factory.newTransformer();
                        //↓DOMのDocumentやNodeを指定。
DOMSource source = new DOMSource(Document);

File newXML = new File("newXML.xml");

FileOutputStream os = new FileOutputStream(newXML);

StreamResult result = new StreamResult(os); 

transformer0.transform(source, result);

  • org.apache.xml.serializeを使用する方法。(Xercesを使用。)
        Java入門参考ページ

      クラスパスに、C:\JAVA\lib\xerces-2_8_0\xercesImpl.jar を追加。

       myコード
       transformer.transform(source, result);

       // 結果DOMツリーの取得
       Document resultDoc = (Document)result.getNode();
       // 出力フォーマットの設定
       OutputFormat formatter = new OutputFormat(resultDoc, "UTF-8", true);
       // 出力ストリーム
       Writer out = new OutputStreamWriter(new FileOutputStream("DOMresult.xml"), "UTF-8");
       // シリアライザの設定
       XMLSerializer serializer = new XMLSerializer(out, formatter);
       // シリアライズ(直列化)
       serializer.serialize(resultDoc);
       // 出力ストリームのクローズ
        out.close();
最終更新:2007年05月01日 21:12