如何使用自定义命名空间序列化

时间:2013-07-23 10:31:37

标签: c# xml namespaces xml-serialization

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

<?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">

我该怎么做?

我尝试在序列化之前向根对象添加属性,还有:

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,不能包含在名称中。”

1 个答案:

答案 0 :(得分:2)

prefic不能包含“:”,取出第一部分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();

确保为每个类添加必需的属性,因为序列化属性不是固有的。有关属性检查的更多信息,请访问:How to deserialize concrete implementation of abstract class from XML

修改

你可以实现xsi:shcemaLocation那样:

 [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";
  }