Java. Embedding an XSL Stylesheet INTERNALLY into an XML Document

时间:2015-06-25 18:15:59

标签: java xml xslt

I want to use Java to embed an XSL Stylesheet internally in an existing XML Document. I found this answer saying it is possible: Embed xsl into an XML file

But I'm using this format, since the example above wasn't working for me. It is pasted below as an example. http://www.calebmadrigal.com/embedding-xslt-xml-document/

    <?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xml" href="#stylesheet"?>
<!DOCTYPE catalog [
<!ATTLIST xsl:stylesheet
  id    ID  #REQUIRED>
]>
<catalog>
<xsl:stylesheet id="stylesheet" version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="artist"/></td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>
</catalog>

I understand you can link to an EXTERNAL stylesheet with a line such as href="MyStyle.xsl" in the xml, but this requires the user to have that file in the same folder as the output xml file.

I would like to embed this stylesheet INTERNALLY so it is viewable in Chrome as the 2nd link above indicates. I'm having problems doing this in java. I'm using the API Eclipse.

I have tried just writing the xsl to the xml document line by line (kind of cutting and pasting the xml document together), but this seems to disrupt with the reading of said document when using a DOM parser, and it's not very elegant. Is this possible?

1 个答案:

答案 0 :(得分:0)

如果使用http://docs.oracle.com/javase/7/docs/api/javax/xml/stream/XMLStreamWriter.html#writeDTD(java.lang.String),您可以写出所需的DOCTYPE节点。我不认为W3C DOM API允许您创建带有嵌入元素和属性声明的DOCTYPE节点。