如何生成带有属性的 xsi:nil 元素?

发布于 2024-09-29 18:20:30 字数 443 浏览 1 评论 0原文

我有一个 WCF 客户端,需要生成包含此 XML 片段的请求:

<reason xsi:nil="true" nullFlavor="NA" typeCode="RSON" />

架构由服务器确定,不受我的控制。生成的代理代码有一个原因元素类,其中包含属性 nullFlavortypeCode。代理使用 XmlSerializer。

我怎样才能生成这样的片段?仅当相应的成员为 null 时,XmlSerializer 才会发出 xsi:nil 属性。如果它为 null,则它不能很好地具有将作为属性发出的属性!

顺便说一句,根据 XML 模式实例规范,该片段是合法的,该规范规定 nil 元素不能包含任何子元素或内部文本,但可以包含属性。

I have a WCF client that needs to generate a request containing this XML fragment :

<reason xsi:nil="true" nullFlavor="NA" typeCode="RSON" />

The schema is determined by the server and isn't under my control. The generated proxy code has a class for the reason element containing (among other things) properties nullFlavor and typeCode. The proxy uses the XmlSerializer.

How can I generate such a fragment? The XmlSerializer emits the xsi:nil attribute only if the corresponding member is null. And if it's null, it can't very well have properties that will be emitted as attributes!

BTW, the fragment is legal according to the XML Schema Instance spec, which says a nil element cannot contain any child elements or inner text, but may contain attributes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-10-06 18:20:30

这是我为那些仍在解决这个问题的人使用的解决方案。这有点麻烦,但它确实有效。关闭 nillable 并添加属性,如下所示

[XmlAttributeAttribute( AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance" )]
public bool NillAtt
{
    get
    {
        return this.nillAtt;
    }
    set
    {
        nillAtt = value;
    }
}

Here is the solution I used for those still struggling with this issue. It is a bit of a hack but it works. Turn off nillable and add and attribute as below

[XmlAttributeAttribute( AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance" )]
public bool NillAtt
{
    get
    {
        return this.nillAtt;
    }
    set
    {
        nillAtt = value;
    }
}
澉约 2024-10-06 18:20:30

这是 XmlSerializer 的已知限制。您也许可以通过巧妙地使用 IXmlSerialized 接口并手动发出 XML 来解决这个问题 - 不幸的是,据我所知,没有一个干净的解决方案。

This is a known limitation of the XmlSerializer. You may be able to get around it with some clever use of the IXmlSerializable interface and emitting the XML manually - unfortunately there isn't a clean solution that I know of.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文