2013-07-04 91 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