问题描述
根据 W3C 标准,如果你有一个 nil 值的可空元素,你应该像这样格式化它:
<myNillableElement xsi:nil="true"/>
但是如果你使用这个 LinqToXml 语句...
element.Add(新 XElement(ns + "myNillableElement", null);
...生成的 XML 是...
<myNillableElement/>
...这是无效的.而且不仅根据 W3C 无效,根据 Microsoft 自己的 XML/XSD 验证器无效.因此,下次验证 XML 时,会出现错误.
我是否缺少一些可以正确处理可空元素的开关?
谢谢.
LINQ to XML 大多不支持模式 - 它允许您验证树,但它不会从中派生任何特定的语义.您的错误是认为 null
应该以某种方式始终映射到 xsi:nil
.W3C 规范中没有这样的要求(很明显,因为它们不涵盖任何类型的语言绑定).
特别是,您调用的 XElement
构造函数实际上采用 object[]
类型的参数,这是一个子列表 - 没有理由传递 null
应该与 xsi:nil
有任何相关性.无论如何,LINQ to XML 应该如何知道您正在生成根据某种架构有效的 XML,并且该架构中的一个特定元素具有 nilled="true"
?p>
According to W3C standards, if you have a nillable element with a nil value, you are supposed to format it like this:
<myNillableElement xsi:nil="true" />
But if you use this LinqToXml statement...
element.Add(
new XElement(ns + "myNillableElement", null);
...the resulting XML is...
<myNillableElement />
...which is invalid. And not just invalid according to W3C, invalid according to Microsoft's own XML/XSD validator. So, next time you validate your XML, you get errors.
Am I missing some switch that can turn on correct handling of nillable elements?
Thanks.
LINQ to XML is mostly not schema-aware - it lets you validate the tree, but it doesn't derive any particular semantics from that. Your mistake is believing that null
should somehow always map to xsi:nil
. There's no such requirement in W3C specs (rather obviously, because they do not cover any kinds of language bindings).
In particular, XElement
constructor that you call actually takes an argument of type object[]
, which is a list of children - there's no reason why passing null
to that should have any relevance to xsi:nil
. In any case, how is LINQ to XML supposed to know that you're producing XML that is valid according to some schema, and that one particular element in this schema has nilled="true"
?
这篇关于LinqToXml 没有按预期处理 nillable 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!