2013-07-04 90 views
2

我有一個將在Java應用程序中處理的XML文檔。 但是,我需要使用XSLT文件對其進行轉換,以便以後可以進行處理。在處理之前用XSLT轉換XML文檔

這就是我現在如何加載XML文件。

DocumentBuilderFactory factory; 
    DocumentBuilder docbuilder; 
    Document doc; 
    Element root; 

    factory = DocumentBuilderFactory.newInstance(); 
    try 
    { 
     // open up the xml document 
     docbuilder = factory.newDocumentBuilder(); 
     doc = docbuilder.parse(new FileInputStream(m_strFileName)); 

     // get the document type 
     doctype = doc.getDoctype(); 
     strDTD = doctype.getPublicId(); 

     // get the root of the document 
     root = doc.getDocumentElement(); 
     // get the list of child nodes 
     nodes = root.getChildNodes(); 
     // now process each node 
     ... 
    } 
    catch(ParserConfigurationException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    catch(SAXException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

如何將XSLT轉換應用於XML文檔,然後獲取新文檔的根節點?

請注意,我是而不是想要將生成的xml樹寫入磁盤。

回答

2

經過一番長時間的研究......終於找到了可接受的解決方案(至少對我而言)。

這是我能夠成功適應樣本:

TransformerFactory factory = TransformerFactory.newInstance(); 
Templates template = factory.newTemplates(new StreamSource(new FileInputStream("xsl.xlt"))); 
Transformer xformer = template.newTransformer(); 
Source source = new StreamSource(new FileInputStream("in.xml")); 
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
Document doc = builder.newDocument(); 
Result result = new DOMResult(doc); 
xformer.transform(source, result); 

從這裏摘自: Transforming an XML File with XSL into a DOM Document

+0

謝謝,這很有幫助。我是否理解正確,產生的文檔現在存儲在'doc'中? (多麼奇怪的API ......) – dokaspar

+1

@dokaspar - 是的,你說得很對,最終的文檔確實保存在變量「doc」中。 – Simon

2

您可以將DOMSource轉換爲DOMResult,請參閱http://docs.oracle.com/javase/6/docs/api/javax/xml/transform/dom/DOMResult.html。請注意,XSLT/XPath使用名稱空間的XML進行操作,以確保您使用可識別名稱空間的文檔生成器工廠。

+0

+1:'DocumentBuilderFactory'是默認_non名稱空間aware_是一些使用趕上我每一次... –

+0

嗨@馬丁,謝謝你不厭其煩地回答這個問題。我正在測試我在上面發佈的解決方案,當您輸入答案時:-D - + 1ed – Simon