LinqToXml 没有按预期处理 nillable 元素

LinqToXml does not handle nillable elements as expected(LinqToXml 没有按预期处理 nillable 元素)
本文介绍了LinqToXml 没有按预期处理 nillable 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 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 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)