使用XmlSerializer在childnode上使用名称空间声明进行序列化

时间:2016-09-12 11:46:41

标签: c# xmlserializer

我正在尝试使用XMLSerializer进行序列化并获得以下结果:

所需的xml:

<?xml version="1.0" encoding="utf-8"?>
<RootElem xmlns="http://www.example.com/rootns">
  <Elem1>
    <Foo>bar</Foo>
  </Elem1>
  <Elem2>
    <x:ElemX xmlns:x="http://www.sample.net/otherns">
      <x:Bar>foo</x:Bar>
    </x:ElemX>
  </Elem2>
</RootElem>

<elem3>中的内容将由另一端的系统单独解析,因此xmlns:x规范必须位于<elemx>节点上,而不是如下所示的根节点上。

当前序列化的xml,不需要:

<?xml version="1.0" encoding="utf-8"?>
<RootElem xmlns:x="http://www.sample.net/otherns" xmlns="http://www.example.com/rootns">
  <Elem1>
    <Foo>bar</Foo>
  </Elem1>
  <Elem2>
    <x:ElemX>
      <x:Bar>foo</x:Bar>
    </x:ElemX>
  </Elem2>
</RootElem>

任何人都知道指示XmlSerializer实现此目标的标准方法吗?

以下是用于生成此示例的代码(简单的c#winform应用程序)

    private void Form1_Load(object sender, EventArgs e)
    {
        RootElem root = new RootElem();

        root.Elem1 = new NormalElement() { Foo = "bar"};

        ChildClass c = new ChildClass() { Bar = "foo"};
        root.Elem2 = new ElementWithChildClass() { ElemX = c };

        MemoryStream ms = new MemoryStream();

        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("x", "http://www.sample.net/otherns");

        XmlSerializer xser = new XmlSerializer(typeof(RootElem));
        XmlTextWriter tw = new XmlTextWriter(ms, Encoding.UTF8);
        tw.Formatting = Formatting.Indented;

        xser.Serialize(tw, root, ns);

        ms.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(ms, Encoding.UTF8);
        textBox1.Text = sr.ReadToEnd();
    }


    [XmlRoot(Namespace = "http://www.example.com/rootns")]
    public class RootElem
    {
        public NormalElement Elem1 { get; set; }
        public ElementWithChildClass Elem2 { get; set; }
    }

    public class NormalElement
    {
        public string Foo { get; set; }
    }

    public class ElementWithChildClass
    {
        [XmlElement(Namespace = "http://www.sample.net/otherns")]
        public ChildClass ElemX  { get; set; }
    }

    [XmlRoot("RefDoc", Namespace = "http://www.sample.net/otherns")]
    public class ChildClass
    {
        public string Bar { get; set; }
    }

0 个答案:

没有答案