不能从已加载的输入文档中删除空格。而是将输入文档提供为XmlReader [英] White space cannot be stripped from input documents that have already been loaded. Provide the input document as an XmlReader instead
问题描述
我想转换XML文档,但是有问题。
I want to transform a XML document, but having a problem.
我的XSLT看起来像这样:
My XSLT looks like this:
<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:strip-space elements="*" />
<xsl:template match="/">
<xsl:apply-templates select="address" />
</xsl:template>
<xsl:template match="address">
<xsl:value-of select="@street" />
<xsl:value-of select="@housenr" />
<xsl:value-of select="@zipcode" />
<xsl:value-of select="@city" />
<xsl:value-of select="@country" />
</xsl:template>
</xsl:stylesheet>
我要转换的XML文档如下所示:
And the XML document I want to transform looks like this:
<address id="4" type="1"
typename="Postadres"
street="pak street"
housenr="420"
zipcode="42000"
city="Nill"
country="Lahore"
kix="" />
这是我写的代码:
public static string Transform(XmlDocument doc, XmlDocument stylesheet)
{
var transform = new System.Xml.Xsl.XslCompiledTransform();
XmlDocument domOutput = new XmlDocument();
stylesheet.PreserveWhitespace = false;
transform.Load(stylesheet); // compiled stylesheet
MemoryStream oStream = new MemoryStream();
var writer = new System.IO.StringWriter();
transform.Transform(doc, (XsltArgumentList)null, oStream);
domOutput.Load(oStream);
return writer.ToString();
}
以下行引发异常
transform.Transform(doc, (XsltArgumentList)null, oStream);
异常消息:
无法从已加载的输入文档中剥离空格。而是将输入文档提供为XmlReader。
White space cannot be stripped from input documents that have already been loaded. Provide the input document as an XmlReader instead.
您能告诉我我在做什么错吗?
Can you tell me what I am doing wrong?
谢谢!
推荐答案
我解决了。实际上, XslCompiledTransform.Transform将XmlReader作为第一个参数,而我正在First Paramenter中传递XmlDocument。
这是代码。
I solved it. Actually "XslCompiledTransform.Transform" takes XmlReader as first Parameter and i was passing XmlDocument in First Paramenter. Here is the code.
public static string Transform(XmlDocument doc, XmlDocument stylesheet)
{
try
{
System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
transform.Load(stylesheet); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlReader xmlReadB = new XmlTextReader(new StringReader(doc.DocumentElement.OuterXml));
transform.Transform(xmlReadB, null, writer);
return writer.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
这篇关于不能从已加载的输入文档中删除空格。而是将输入文档提供为XmlReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!