Self closing tags in xsl method: xml

五迷三道 提交于 2019-12-06 02:56:44

It is not available by default with method=xml. You can handle it in a couple of ways:

Option 1 - switch to method=xhtml

If you can't switch to method=xml, and you are using XSLT 2.0 parser, maybe you can try method=xhtml?

<xsl:output method="xhtml" indent="yes" />

This will make your closing tags to be rendered.

Option 2 - add empty space to 'div' tag

Alternatively just add <xsl:text> </xsl:text> (with one space in between tags) to make your <div> not empty (of course if space there is okay with you).

Consider following XML:

<div></div>

When transformed with:

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

  <!-- output is xml -->
  <xsl:output method="xml" indent="yes" />

  <xsl:template match="div">
    <div>
      <!-- note space here -->
      <xsl:text> </xsl:text>
      <xsl:value-of select="text()" />
    </div>
  </xsl:template>
</xsl:stylesheet>

It produces output:

<?xml version="1.0" encoding="UTF-8"?>
<div> </div>

I have had the same issue. The problem is the XmlTextWriter which only messes up the html. Try the following code:

public static string Transform(string xmlPath, string xslPath, XsltArgumentList xsltArgumentList)
    {
        string rc = null;
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            XPathDocument myXPathDoc = new XPathDocument(xmlPath);
            XslCompiledTransform myXslTrans = new XslCompiledTransform();
            myXslTrans.Load(xslPath, new XsltSettings(true, true), null);
            myXslTrans.Transform(myXPathDoc, xsltArgumentList, ms);
            ms.Position = 0;
            using (System.IO.TextReader reader = new System.IO.StreamReader(ms, Encoding.UTF8))
            {
                rc = reader.ReadToEnd();
            }
        }
        return rc;
    }

I use the XsltArgumentList to pass information to the xslt. If you do not need to pass arguments to your xslt, you may call the method like this:

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