問題描述
根據 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 元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!