小编典典

在.NET中序列化对象时忽略所有xsi和xsd名称空间?

c#

代码如下:

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);
}

生成的序列化文档包括名称空间,如下所示:

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

要删除xsi和xsd命名空间,我可以遵循如何在不获取xmlns
=”…”的情况下将对象序列化为XML
的答案

我希望我的消息标签为<message>(没有任何名称空间属性)。我怎样才能做到这一点?


阅读 290

收藏
2020-05-19

共1个答案

小编典典

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