Is it possible to embed xml xsl transformed into a

2019-09-10 16:42发布

I am wondering if there is possible such situation where I can place inline xml linked with xsl into the body of html, like:

<html>
 <body>
  text
  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <?xml-stylesheet type="text/xsl" href="articles.xsl"?>
  <articles>
   <article title="title"/>
  </articles>
  text
 </body>
</html>

标签: html xml xslt
2条回答
一纸荒年 Trace。
2楼-- · 2019-09-10 17:31

See section 2.4 of

http://www.w3.org/TR/2012/NOTE-html-xml-tf-report-20120209/

The two approaches suggested there are

(a) Put the XML inside a script element

(b) Use XHTML.

Direct nesting of XML inside the HTML as in your example is not advised because the HTML parser will treat the XML as bad HTML, and try to repair it.

查看更多
别忘想泡老子
3楼-- · 2019-09-10 17:42

As Michael Kay suggested, you can embed the XML in XHTML and apply the stylesheet to the entire document. Then you can apply an XSL transformation to the entire document, applying the identity transform to all HTML elements and specific templates to the embedded non-HTML elements.

Here is an example:

Input XHTML

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="ie8fix.xsl"?>
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>test</title>
  </head>
  <body>
    text
    <articles xmlns="">
      <article title="title"/>
    </articles>
    text
  </body>
</html>

XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.w3.org/1999/xhtml">

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="articles">
    <div class="articles">
      <h1>articles</h1>
      <xsl:apply-templates select="article" mode="transform"/>
    </div>
  </xsl:template>

  <xsl:template match="article" mode="transform">
    <article><!-- HTML5 article element -->
      <h2><xsl:value-of select="@title"/></h2>
      <xsl:apply-templates select="node()" mode="transform"/>
    </article>
  </xsl:template>
</xsl:stylesheet>

Output XHTML

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="ie8fix.xsl"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
      <title>test</title>
  </head>
  <body>
    text
    <div class="articles">
         <h1>articles</h1>
         <article>
            <h2>title</h2>
         </article>
      </div>
    text
  </body>
</html>

Another option would be to transform the XML after loading the page using JavaScript and XSLTProcessor.

查看更多
登录 后发表回答