如何在C#中为我的类实现以下XmlSerializer更改?

时间:2017-05-03 21:45:06

标签: c# .net xml xml-serialization xmlserializer

我想生成以下XML:

<Base>
    <Child>
        <Name>Joe</Name>
    </Child>
    <Child>
        <Name>Jack</Name>
    </Child>
</Base>

来自班级:

public class Base
{
    public List<Child> children;
    ...elided...
}

public class Child
{
    public string Name;
    ...elided...
}

现在,它正在创造:

<Base>
    <children>
        <Child>
            <Name>Joe</Name>
        </Child>
        <Child>
            <Name>Jack</Name>
        </Child>
    </children>
</Base>

如何更改以产生所需的输出?

我目前的代码:

XmlSerializer serializer = new XmlSerializer(base.GetType());
serializer.serialze(stringWriter, base);
return stringWriter.ToString();

3 个答案:

答案 0 :(得分:4)

使用XmlElementAttribute

public class Base
{
    [XmlElement(ElementName = "Child")]
    public List<Child> children;
}

......完整的例子......

using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

class Program
{
    static void Main()
    {
        var xsr = new XmlSerializer(typeof(Base));

        var b = new Base
        {
            children = new List<Child>
                {
                    new Child { Name= "Joe"},
                    new Child { Name ="Jack"},
                }
        };
        using (var ms = new MemoryStream())
        {
            xsr.Serialize(ms, b);

            var str = Encoding.UTF8.GetString(ms.ToArray());
            /*
            <?xml version="1.0"?>
            <Base xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
              <Child>
                <Name>Joe</Name>
              </Child>
              <Child>
                <Name>Jack</Name>
              </Child>
            </Base>
             */
        }
    }
}

public class Base
{
    [XmlElement("Child")]
    public List<Child> children;
}

public class Child
{
    public string Name;
}

答案 1 :(得分:2)

您可以按如下方式使用XmlElementAttribute:

public class Base
{
    [XmlElement("Child")]
    public List<Child> children;
    ...elided...
}

public class Child
{
    public string Name;
    ...elided...
}

答案 2 :(得分:0)

编辑:其他解决方案可以更好,更直接地回答您的问题。但是,我将在此处留下这一点,因为扩展了List&lt;&gt;在某些情况下,而不是包括公共列表成员可能是一个好主意。这是可能的解决方案。

好吧,你可以实现IXmlSerializable,但这可能对你正在寻找的事情有些过分。或者,您可以制作Base扩展列表&lt; Child&gt;。

public class Base : List<Child>
{
}

当然,这将改变您在其余代码中引用子代的方式。如果你有base.children [0],你可以使用base [0]。

相关问题