我有一个XSLT,它将XML从外部应用程序转换为我自己的对象,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="SimpleObject">
<NewSimpleObject>
<NewField1>
<xsl:value-of select="OldField1"/>
</NewField1>
<NewField2>
<xsl:value-of select="OldField2"/>
</NewField2>
</NewSimpleObject>
</xsl:template>
</xsl:stylesheet>
传入的XML非常简单,尽管它有很多我没有使用的字段。
<?xml version="1.0" encoding="UTF-8"?>
<SimpleObject>
<OldField1>Test</OldField1>
<OldField2>Value</OldField2>
<OldField3/>
<OldField4/>
<OldField5/>
<OldField6/>
<OldField7/>
</SimpleObject>
当我尝试在C#中应用XSLT时,出现以下错误:
Token Text in state Start 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.
这是我正在执行的代码:
public string ApplyTransform(string xml, string operationName)
{
var result = string.Empty;
var resourceName = GetResourceNameFromOperationName(operationName);
using (var stringReader = new StringReader(xml))
{
using (var xmlReader = XmlReader.Create(stringReader))
{
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter))
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
using (var xslReader = XmlReader.Create(stream))
{
var compiledTransform = new XslCompiledTransform();
compiledTransform.Load(xslReader);
compiledTransform.Transform(xmlReader, xmlWriter);
result = stringWriter.ToString();
}
}
}
}
}
}
return result;
}