本文介绍了如何删除 xmlns:xsd 属性但保留 xmlns:xsi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# Windows 窗体应用程序中使用 .Net XmlSerializer 将对象序列化为 XML 文档.

I am using the .Net XmlSerializer to serialize an object to an XML document, in a C# Windows Forms application.

根元素应该看起来像:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="file:///C:/data//MySchema.xsd">
  <!-- ... -->
</root>

在分部类中(为了加入由 xsd.exe 创建的分部类),我添加了以下属性来添加 xsi:noNamespaceSchemaLocation 属性.>

In a partial class (to join the partial class created by xsd.exe), I have added the following property to add the xsi:noNamespaceSchemaLocation attribute.

[XmlAttribute("noNamespaceSchemaLocation", Namespace = XmlSchema.InstanceNamespace)]
public string xsiNoNamespaceSchemaLocation = @"file:///C://data//MySchema.xsd";

并删除所有其他命名空间,但保留我使用过的 xsi :

And to remove all the other namespaces, but keep the xsi one I have used:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

然后将 ns 传递给 XmlSerializer.Serialize() 方法.

And then passed ns to the XmlSerializer.Serialize() method.

到目前为止,这有效,但我不确定这是否正确.感觉就像我正在删除默认情况下的内容,只是为了尝试再次添加其中的一部分......似乎是一种代码气味.

This works so far, but I'm not sure if this is correct. It feels like I'm removing what is there by default, only to try add a piece of it back again... seems like a code smell.

也许有更好的方法只删除 xsd 但保留默认的 xsi,所以我不需要再次添加它?

Maybe is there a better way that only removes the xsd but leaving the default xsi, so I don't need to add it back in again?

注意:很久以前就有一个关于此的未回答问题此处,唯一建议的答案不适合,因为它删除了 xsd xsi 属性.

Note: There is an unanswered question on this already from some time back here, the only suggested answer does not suit as it removes both xsd and xsi attributes.

推荐答案

你所做的在我看来是正确的.

What you've done looks correct to me.

您可以查看内部结构并看到 XmlSerializer 使用 DefaultNamespaces 当没有指定时.

You can look at the internals and see that XmlSerializer uses DefaultNamespaces when none are specified.

这与您要为 xsixsd 提供包含前缀/命名空间的 XmlSerializerNamespaces 相同,这就是您看到声明的原因默认用于 xsixsd.

This is the same as if you were to supply and XmlSerializerNamespaces containing prefixes / namespaces for xsi and xsd and is why you see declarations for xsi and xsd by default.

删除"xsd 的正确做法是提供一个不包含该前缀/命名空间的 XmlSerializerNamespaces 实例.

The correct thing to do to 'remove' xsd would be to supply an XmlSerializerNamespaces instance that doesn't contain that prefix / namespace.

这篇关于如何删除 xmlns:xsd 属性但保留 xmlns:xsi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 18:09