我一直在四處尋找Java示例以使用XSLT轉換XML文檔。我發現了幾個使用new File("path/to/file.xml")
的樣本來加載XML和XSLT,並且這些樣本很好。我的問題是,我試圖用一種新的方法來使用這個方法,它將接受兩個org.w3c.dom.Document
對象。只要將用於加載XSLT的StreamSource
替換爲DOMSource
,我的調用結果就是XSLT,而不是轉換的XML。從How to call XSL template from java code?使用DOM在Java中使用XSLT轉換XML
工作代碼:
Source xmlInput = new StreamSource(new File("c:/path/to/input.xml"));
Source xsl = new StreamSource(new File("c:/path/to/file.xsl"));
Result xmlOutput = new StreamResult(new File("c:/path/to/output.xml"));
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer(xsl);
transformer.transform(xmlInput, xmlOutput);
} catch (TransformerException e) {
// Handle.
}
我的代碼:
public static Document transformXML(Document xml, Document xslt) throws TransformerException, UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException, FactoryConfigurationError{
Source xmlSource = new DOMSource(xml);
Source xsltSource = new DOMSource(xslt);
StreamResult result = new StreamResult(new StringWriter());
// the factory pattern supports different XSLT processors
TransformerFactory transFact =
TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
trans.transform(xmlSource, result);
Document resultDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(result.getWriter().toString().getBytes("utf-8")));
return resultDoc;
}
我的結果文件,則XSLT,而不是XML。我在做什麼錯了DOMSource
?
您是否向使用名稱空間感知文檔生成器構建的變換器提供的DOM樹?如果你想要一個'Document'節點作爲結果,爲什麼不直接使用'DOMResult result = new DOMResult(); trans.transform(xmlSource,result); Document resultDoc =(Document)result.getNode();'? –
@MartinHonnen非常好的一點。我更新了代碼。現在出於某種可怕的原因,我的resultDoc仍然是XSLT。這就像變壓器_switches_他們了!? – GuillaumeC91