【发布时间】:2019-04-12 05:18:11
【问题描述】:
我正在使用 XSLT 文件将 XML 文件转换为另一个 XML 文件,然后在本地创建此 XML 文件。我收到此错误:
System.InvalidOperationException: '处于 Start 状态的令牌文本将导致无效的 XML 文档。如果要编写 XML 片段,请确保将 ConformanceLevel 设置设置为 ConformanceLevel.Fragment 或 ConformanceLevel.Auto。 '
XSLT 文件在 Visual Studio 中进行了调试,看起来可以正常工作,但我不明白这个错误。这是什么意思,如何解决?
这是我的 XML:
<?xml version="1.0" encoding="utf-8"?>
<In xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="take.xsd">
<Submit ID="1234">
<Values>
<Code>34</Code>
<Source>27</Source>
</Values>
<Information>
<Number>55</Number>
<Date>2018-05-20</Date>
<IsFile>1</IsFile>
<Location></Location>
<Files>
<File>
<Name>Red.pdf</Name>
<Type>COLOR</Type>
</File>
<File>
<Name>picture.pdf</Name>
<Type>IMAGE</Type>
</File>
</Files>
</Information>
</Submit>
</In>
我的 XSLT 代码:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<!-- identity template - copies all elements and its children and attributes -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="/In">
<!-- Remove the 'In' element -->
<xsl:apply-templates select="node()"/>
</xsl:template>
<xsl:template match="Submit">
<!-- Create the 'Q' element and its sub-elements -->
<Q xmlns:tns="Q" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://schema.xsd" Source="{Values/Source}" Notification="true">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="Values" />
<xsl:apply-templates select="Information" />
<xsl:apply-templates select="Information/Files" />
</xsl:copy>
</Q>
</xsl:template>
<xsl:template match="Information">
<!-- Create the 'Data' sub-element without all of its children -->
<xsl:copy>
<xsl:copy-of select="Number"/>
<xsl:copy-of select="Date"/>
<xsl:copy-of select="IsFile"/>
<xsl:copy-of select="Location"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这是用于转换文件的 C# 代码:
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(@"D:\\Main\XLSTFiles\Test.xslt");
string xmlPath = @"D:\Documents\Test2.xml";
using (XmlWriter w = XmlWriter.Create(@"D:\Documents\NewFile.xml"))
{
xslt.Transform(xmlPath, w);
}
另外,有没有办法生成具有适当缩进的新 XML 文件?它似乎在最后一个节点关闭后创建每个节点,并且在自定义模板上它只是一个接一个地附加每个项目。
【问题讨论】:
-
Transform方法有一个重载xslt.Transform(@"D:\Documents\Test2.xml", @"D:\Documents\NewFile.xml"),所以使用它而不是创建您自己的 XmlWriter,这样 XslCompiledTransform 将在内部使用您的xsl:output中的正确设置创建一个。您收到的消息表明您的 XSLT 创建了一个包含多个顶级元素的片段,如果您想使用自己的 XmlWriter 来获得这样的结果,您需要使用正确的 XmlWriterSettings 和ConformanceLevel.Fragment。 -
谢谢@MartinHonnen。出于某种原因,将转换切换到您建议的重载转换甚至在不更改 XmlWriterSettings 的情况下摆脱了我的片段错误。甚至应该以这种方式发生吗?它生成的文件看起来也正确。