[英]Problem with XElement and XslCompiledTransform
I'm having some trouble using a combination of XElement
and XslCompiledTransform
. 我在结合使用
XElement
和XslCompiledTransform
遇到了一些麻烦。 I've put the sample code I'm using below. 我在下面放了我正在使用的示例代码。 If I get my input XML using the
GetXmlDocumentXml()
method, it works fine. 如果我使用
GetXmlDocumentXml()
方法获取输入XML,则可以正常工作。 If I use the GetXElementXml()
method instead, I get an InvalidOperationException
when calling the Transform
method of XslComiledTransform
: 如果我改用
GetXElementXml()
方法,则在调用XslComiledTransform
的Transform
方法时收到InvalidOperationException
:
Token Text in state Start would result in an invalid XML document. 状态为“开始”的令牌文本将导致无效的XML文档。 Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment .
如果要编写XML片段,请确保将ConformanceLevel设置设置为ConformanceLevel.Fragment或ConformanceLevel.Auto 。
The CreateNavigator
method on both XElement
and XmlDocument
returns an XPathNavigator
. XElement
和XmlDocument
上的CreateNavigator
方法都返回XPathNavigator
。 What extra stuff is XmlDocument
doing so this all works, and how can I do the same with XElement
? XmlDocument
还能做些什么额外的工作,使它们全部起作用,如何使用XElement
做到这一点? Am I just doing something insane? 我只是在做疯狂的事情吗?
static void Main(string[] args)
{
XslCompiledTransform stylesheet = GetStylesheet(); // not shown for brevity
IXPathNavigable input = this.GetXElementXml();
using (MemoryStream ms = this.TransformXml(input, stylesheet))
{
XmlReader xr = XmlReader.Create(ms);
xr.MoveToContent();
}
}
private MemoryStream TransformXml(
IXPathNavigable xml,
XslCompiledTransform stylesheet)
{
MemoryStream transformed = new MemoryStream();
XmlWriter writer = XmlWriter.Create(transformed);
stylesheet.Transform(xml, null, writer);
transformed.Position = 0;
return transformed;
}
private IXPathNavigable GetXElementXml()
{
var xml = new XElement("x", new XElement("y", "sds"));
return xml.CreateNavigator();
}
private IXPathNavigable GetXmlDocumentXml()
{
var xml = new XmlDocument();
xml.LoadXml("<x><y>sds</y></x>");
return xml.CreateNavigator();
}
Oh, that was easy. 哦,那很容易。 The solution was to wrap the
XElement
in an XDocument
object. 解决方案是将
XElement
包装在XDocument
对象中。 Problem solved! 问题解决了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.