【发布时间】: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。这就是您默认看到xsi和xsd的原因。 -
@CharlesMager 谢谢,看着我意识到我可以将命名空间添加到:
ns.Add("xsi", XmlSchema.InstanceNamespace); -
@CharlesMager 已经阅读了更多内容,您的评论似乎是在 FWIW 上发现的,如果您想将其作为答案,我会接受。
标签: c# xml xsd schema xml-namespaces