如何使用自定义名称空间进行序列化 [英] How to serialise with custom namespace

查看:146
本文介绍了如何使用自定义名称空间进行序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个对象序列化为XML,并得到如下输出:

I am serialising an object to XML and I get the output like so :

<?xml version="1.0" encoding="utf-8"?>
<SOrd xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

但是我希望这样:

<SOrd xmlns:SOrd="http://..." xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://....xsd">

我该怎么做?

我曾尝试在序列化之前将属性添加到根对象,这也是这样:

I have tried adding attributes to the root object before serialisation and also this :

XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("xmlns:SOrd", "http://...");
xmlNameSpace.Add("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNameSpace.Add("xsi:schemaLocation", "http://....xsd");

XmlSerializer xs = new XmlSerializer(ord.GetType());
TextWriter writer = new StreamWriter(outputPath, false);
xs.Serialize(writer, ord, xmlNameSpace);
writer.Close();

但是我得到一个例外名称中不能包含':'字符,十六进制值0x3A."

推荐答案

优先级不能包含:",取出第一部分xmlns:

the prefic can't contain the ":", take out the first part xmlns:

这是您的代码已更改:

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

XmlSerializer xs = new XmlSerializer(ord.GetType());
TextWriter writer = new StreamWriter(outputPath, false);
xs.Serialize(writer, ord, xmlNameSpace);
writer.Close();

请确保为每个类添加必需的属性,因为不包含序列化属性.有关属性继承的更多信息,请检查:如何反序列化XML抽象类的具体实现

make sure to add the required attributes for each class since the serialization attributes are not inhereted. for more about the inheretence of attributes check: How to deserialize concrete implementation of abstract class from XML

编辑

您可以像这样实现xsi:shcemaLocation:

you can achieve the xsi:shcemaLocation Like that:

 [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar", DataType = "schemaLocation")]  
  public class Foo
  {
    [System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string schemaLocation = "http://example";
  }

这篇关于如何使用自定义名称空间进行序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆