【问题标题】:How to remove the xmlns:xsd attribute but keep xmlns:xsi如何删除 xmlns:xsd 属性但保留 xmlns:xsi
【发布时间】:2018-01-17 06:17:43
【问题描述】:

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

根元素最终应该看起来像:

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

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

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

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

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

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

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

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

注意:很久以前就有一个未回答的问题here,唯一建议的答案不适合,因为它同时删除了xsd xsi 属性。

【问题讨论】:

  • 你所做的在我看来是正确的。您可以查看内部结构,发现XmlSerializer 在未指定时使用DefaultNamespaces。这就是您默认看到xsixsd 的原因。
  • @CharlesMager 谢谢,看着我意识到我可以将命名空间添加到:ns.Add("xsi", XmlSchema.InstanceNamespace);
  • @CharlesMager 已经阅读了更多内容,您的评论似乎是在 FWIW 上发现的,如果您想将其作为答案,我会接受。

标签: c# xml xsd schema xml-namespaces


【解决方案1】:

在我看来,您所做的一切都是正确的。

您可以查看内部结构,发现XmlSerializer 在未指定时使用DefaultNamespaces

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

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

【讨论】:

    【解决方案2】:

    我也遇到了像你这样的问题。我首先使用了linq,但它不起作用。后来我发现了一个更好的工具XSLT。你可以像Online一样使用XSLT

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      相关资源
      最近更新 更多