状态EndRootElement中的Token StartElement在尝试使用XSLT将XML转换为HTML时会导致无效的XML Document [...]错误

时间:2017-04-03 15:46:27

标签: html xml xslt

我正在尝试通过XSLT将XML转换为HTML。

我的XML是:

<FooterXmlModel>
  <Utente>foo@bar.it</Utente>
  <Today>03/04/2017 17:18:37</Today>
</FooterXmlModel>

我的xslt是:

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

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" />
  <xsl:template match="/">
  <!--Footer-->
  <div>
    <b>User: </b>
    <p>© All Rights Reseved. P.IVA xxxyyyzzzwww</p>   -
    <xsl:value-of select="/FooterXmlModel/Utente"/>   -
    <xsl:value-of select="/FooterXmlModel/Today"/>
  </div>
  <hr style=" width 100%; height:2px; border-style:solid; margin:1px;clear:left;" />
  <div>
   <span>http://new.foo.it</span>
  </div>
  </xsl:template>
</xsl:stylesheet>

我有一个函数接受xml文档及其xslt并尝试在html文档中转换它:

public string TransformToHtml(IPrintablePartXml document, IXPathNavigable xsltStyleSheet)
        {
            //XML Containing the actual document
            var xmlDoc = document.GetXmlContent();
            //resulting html file
            string htmlDoc = String.Empty;

            XPathNavigator xmlContent = new XPathDocument(new XmlTextReader(new StringReader(xmlDoc))).CreateNavigator();

            using (MemoryStream xslFoStream = new MemoryStream())
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = new UTF8Encoding(false);
                settings.ConformanceLevel = ConformanceLevel.Document;
                settings.Indent = true;

                using (XmlWriter xwriter = XmlWriter.Create(xslFoStream, settings))
                {
                    XslCompiledTransform transformer = new XslCompiledTransform(false);

                    transformer.Load(xsltStyleSheet);
                    transformer.Transform(xmlContent, _xsltExtensions, xwriter);

                    xwriter.Flush();

                    xslFoStream.Position = 0;

                    StreamReader sr = new StreamReader(xslFoStream);
                    htmlDoc = sr.ReadToEnd();
                }

                return htmlDoc;
            }

        }

当我调用transformer.Transform(xmlContent,_xsltExtensions,xwriter)时出现此错误:

Token StartElement in state EndRootElement would result in an invalid
XML document. Make sure that the ConformanceLevel setting is set to 
ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write
an XML fragment.

我已经阅读了有关此主题的所有先前问题,但我无法弄清楚为什么我会收到此错误,因为在我看来,我的XML格式正确。

1 个答案:

答案 0 :(得分:2)

您的XSLT样式表尝试创建一个XML片段,该片段由2个div元素组成,由hr分隔 - 所有三个元素都是树的顶层兄弟。 well-formed XML document只有一个根元素:

  

[定义:只有一个元素,称为根,或   文档元素,其中任何一部分都不会出现在其他内容中   元件。]