省略所有XSI和XSD的命名空间序列化的.NET对象时?对象、序列化、空间、XSI

2023-09-02 01:21:07 作者:纯情小处男

在code是这样的:

  StringBuilder的建设者=新的StringBuilder();
XmlWriterSettings设置=新XmlWriterSettings();
settings.OmitXmlDeclaration = TRUE;
使用(的XmlWriter的XmlWriter = XmlWriter.Create(建设者,设置))
{
    XmlSerializer的S =新的XmlSerializer(objectToSerialize.GetType());
    s.Serialize(XMLWriter的,objectToSerialize);
}
 

由此产生的序列化文件包括命名空间,就像这样:

 <消息的xmlns:XSI = HTTP://www.w3.org/2001/XMLSchema-instance 
    的xmlns:XSD = HTTP://www.w3.org/2001/XMLSchema 
    的xmlns =金塔:什么>
 ...
< /消息>
 

要删除XSI和XSD的命名空间,我可以按照回答如何没有得到的xmlns =...序列化对象到XML? 。

我希望我的邮件标记为<消息> (不带任何命名空间属性)。我怎样才能做到这一点?

解决方案

  ...
XmlSerializer的S =新的XmlSerializer(objectToSerialize.GetType());
XmlSerializerNamespaces NS =新XmlSerializerNamespaces();
ns.Add(,);
s.Serialize(XMLWriter的,objectToSerialize,NS);
 
未能找到类型或命名空间名称 Sqlcommand 是否缺少 using 指令或程序集引用 该添加什么引用

The code looks like this:

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using (XmlWriter xmlWriter = XmlWriter.Create(builder, settings))
{
    XmlSerializer s = new XmlSerializer(objectToSerialize.GetType());
    s.Serialize(xmlWriter, objectToSerialize);
}

The resulting serialized document includes namespaces, like so:

<message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns="urn:something">
 ...
</message>

To remove the xsi and xsd namespaces, I can follow the answer from How to serialize an object to XML without getting xmlns="…"?.

I want my message tag as <message> (without any namespace attributes). How can I do this?

解决方案

...
XmlSerializer s = new XmlSerializer(objectToSerialize.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
s.Serialize(xmlWriter, objectToSerialize, ns);