XDocument 构造函数出现意外异常
这工作正常:
XDocument xdoc = new XDocument(
new XDeclaration("1.1", "UTF-8", "yes"),
new XProcessingInstruction("foo", "bar"),
new XElement("test"));
但是,如果我将其更改为将“params array”显式作为数组传递:
object[] content = new object[] {
new XDeclaration("1.1", "UTF-8", "yes"),
new XProcessingInstruction("foo", "bar"),
new XElement("test")
};
xdoc = new XDocument(content);
它会失败:
System.ArgumentException:无法将非空白字符添加到内容中。
这两个例子不是完全等同的吗?这是怎么回事?
This works fine:
XDocument xdoc = new XDocument(
new XDeclaration("1.1", "UTF-8", "yes"),
new XProcessingInstruction("foo", "bar"),
new XElement("test"));
However if I change it to pass the "params array" explicitly as an array:
object[] content = new object[] {
new XDeclaration("1.1", "UTF-8", "yes"),
new XProcessingInstruction("foo", "bar"),
new XElement("test")
};
xdoc = new XDocument(content);
It fails with:
System.ArgumentException: Non white space characters cannot be added to content.
Aren't these two examples exactly equivalent? What's going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用
XDocument
构造函数而不是工厂方法,则在解析 XML 字符串时可能会出现此错误。鉴于:
这失败了:
这有效:
You can get this error when parsing XML strings if you use the
XDocument
constructor instead of a factory method.Given:
This fails:
This works:
当您使用第一种方法时,您将使用 XDocument 的重载,它首先接受 XDeclaration,然后接受内容的参数。但是,当您使用第二种方法时,您正在使用带有内容参数的重载。 object[] 数组中的 XDeclaration 作为内容传入,这就是它爆炸的地方。
请参阅此处:http://msdn.microsoft。 com/en-us/library/system.xml.linq.xdocument.xdocument.aspx
When you use the first method, you're using the overload of XDocument that first takes an XDeclaration and then a params for the content. However, when you're using the second approach, you're using the overload which takes a params for content. The XDeclaration in your object[] array is coming through as content, and that's where it's blowing up.
See here : http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.xdocument.aspx