2014-02-12 116 views
2

請幫助使用Apache公理生成XML文件,用一個父母和兩個子標籤任何XML文件,我想下面的代碼示例XML文件生成

OMFactory factory = OMAbstractFactory.getOMFactory(); 
OMNamespace ns1 = factory.createOMNamespace("bar","x"); 
OMElement root = factory.createOMElement("root",ns1); 
OMNamespace ns2 = root.declareNamespace("bar1","y"); 
OMElement elt1 = factory.createOMElement("foo",ns1); 
OMElement elt2 = factory.createOMElement("yuck",ns2); 
OMText txt1 = factory.createOMText(elt2,"blah"); 
elt2.addChild(txt1); 
elt1.addChild(elt2); 
root.addChild(elt1); 

請幫我如何序列OMElment是非序列化api類的根元素。 請幫我舉個例子。

回答

3
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.OutputStream; 

import javax.xml.stream.XMLStreamException; 

import org.apache.axiom.om.OMAbstractFactory; 
import org.apache.axiom.om.OMElement; 
import org.apache.axiom.om.OMFactory; 
import org.apache.axiom.om.OMNamespace; 
import org.apache.axiom.om.OMText; 


public class Example { 
    public static void main(String[] args) { 
     try { 
      OMFactory factory = OMAbstractFactory.getOMFactory(); 

      OMNamespace ns1 = factory.createOMNamespace("bar", "x"); 
      OMElement root = factory.createOMElement("root", ns1); 
      OMNamespace ns2 = root.declareNamespace("bar1", "y"); 

      OMElement elt1 = factory.createOMElement("foo", ns1); 
      OMElement elt2 = factory.createOMElement("yuck", ns2); 
      OMElement elt3 = factory.createOMElement("yuck2", ns2); 

      OMText txt1 = factory.createOMText(elt2, "blah"); 
      OMText txt2 = factory.createOMText(elt3, "blah-blah"); 

      elt2.addChild(txt1); 
      elt3.addChild(txt2); 
      elt1.addChild(elt2); 
      elt1.addChild(elt3); 

      root.addChild(elt1);  

      OutputStream outputStream = null; 
      try { 
       outputStream = new FileOutputStream("C:\\xml.xml"); 
      } catch (FileNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      root.serialize(outputStream); 

      root.serialize(System.out); 

     } catch (XMLStreamException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

控制檯輸出:

<x:root xmlns:x="bar" xmlns:y="bar1"><x:foo><y:yuck>blah</y:yuck><y:yuck2>blah-blah</y:yuck2></x:foo></x:root>

序列化的文件:

<x:root xmlns:x="bar" xmlns:y="bar1"> 
    <x:foo> 
     <y:yuck>blah</y:yuck> 
     <y:yuck2>blah-blah</y:yuck2> 
    </x:foo> 
</x:root>  

詳情

+0

謝謝,它是爲我工作,你的序列化文件解釋根元素問題。 – Shekkar

+0

不客氣。 –