JAXP Transformer via DOMSource returns stylesheet

邮差的信 提交于 2020-02-02 11:36:05

问题


I'm having a strange problem and can't seem to find any solution. I'm simply trying to apply an XSLT stylesheet to an XML file (in this case, SPARQL query results formatted as XML, but any other XML file gives the same result). In this case, I need to create the transformer by re-using an already loaded XML document, via DOMSource. You can find the code below (simplified; normally, the stylesheet document comes from elsewhere):

TransformerFactory factory = TransformerFactory.newInstance();
Document stylesheet = db.parse(new File("C:/workspace_5/stylesheet.xml"));
Transformer xformer = factory.newTransformer(new DOMSource(stylesheet));

Source source = new StreamSource(new FileInputStream("C:/workspace_5/xml-file.xml"));        
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
Result result = new StreamResult(bOut);

xformer.transform(source, result);

Instead of the transformed XML, the StreamResult's outputstream returns the loaded stylesheet. If I replace the second and third line by:

Transformer xformer = factory.newTransformer(new StreamSource(
    new FileInputStream(""C:/workspace_5/stylesheet.xml")));

Then everything works just fine. And yes, of course I could serialize the loaded stylesheet document into a string, convert it to a ByteArrayInputStream (or even worse, write it to a file), and then use that to create a StreamSource, but that's just silly.

Is there any reason this is not working?

The xml-file.xml code:

<?xml version="1.0"?>
<sparql>
  <head>
    <variable name="buyerName"/>
  </head>
  <results>
    <result>
      <binding name="buyerName">
        <literal>John Doe</literal>
      </binding>
    </result>
  </results>
</sparql>

The stylesheet.xml code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:po="http://www.w3.org/2002/ws/sawsdl/spec/wsdl/order#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<xsl:template match="/sparql">
    <xsl:for-each select="results/result">

        <buyer xsi:type="po:Buyer">
            <name xsi:type="string"><xsl:value-of select="binding[@name='buyerName']/literal" /></name>
        </buyer>

    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Thanks!

William


回答1:


Your DocumentBuilderFactory is most likely not namespace aware. Try turning on namespace awareness with:

factory.setNamespaceAware(true);

You can check out this post for the related code.



来源:https://stackoverflow.com/questions/12174297/jaxp-transformer-via-domsource-returns-stylesheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!