序列化类对象给出错误的xml

时间:2014-05-20 14:59:39

标签: c# xml serialization xml-serialization xmlserializer

在silverlight中,我有xml,如:

<A>
    < A1>
       <B>
        < B1>a1.1</B1>
        <B1>a1.2</B1>
        </B>
    < /A1>

    < A1>
          <B>
          <B1>a1.3< /B1>
          <B1>a1.4</B1>
          </B>
    </A1>
</A>

我的班级是这样的 A.cs

namespace Check
{
  [XmlRoot(ElementName = "A")]
  public class A
  {

    [XmlElement("A1")]
       public List<A1> A1 { get; set; } 

  }
}

和A1.cs是:

namespace Check
{
  [XmlRoot(ElementName = "A1")]
  public class A1
  {  
        [XmlArray("B")]
        [XmlArrayItem("B1", typeof(string))]
        public List<string> B { get; set; }

  }
}

B.cs类是

namespace Check
{
  [XmlRoot(ElementName = "B")]
  public class B
  {

        [XmlArray("B")]
        [XmlArrayItem("B1", typeof(string))]
        public List<string> B1 { get; set; }

  }
}

我尝试在Xml.cs中序列化ike:

namespace Check
{
    public static class Xml
    {
        public static string ToXml(this object objectToSerialize)
        {
             var memory = new MemoryStream();
             var serial = new XmlSerializer(objectToSerialize.GetType());
             serial.Serialize(memory, objectToSerialize);  
            var utf8 = new UTF8Encoding();
            return utf8.GetString(memory.GetBuffer(), 0, (int)memory.Length);  
        }
    }
}

Ans Main Function类是:

namespace Check
{
    public  class ControlClass
    {
        public  void Main()
        {
            var a = new A() ;
            var xml = a.ToXml();

         }
    }
}

我的序列化方法是否正确?如果没有,请纠正我?

我的输出是:

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

1 个答案:

答案 0 :(得分:1)

是的,这是正确的......是的。它没有显示更多内容的原因是因为您的A实例只有一个属性(A1),并且具有null值。添加数据,它出现:

var a = new A {
    A1 = new List<A1> {
        new A1 { B = new List<string> { "a1.1", "a1.2" } },
        new A1 { B = new List<string> { "a1.3", "a1.4" } }
    }
};

即使是空名单也会有所帮助。因此,您可能更愿意使用:

[XmlElement("A1")]
public List<A1> A1 { get { return a1; } }
private readonly List<A1> a1 = new List<Check.A1>();

[XmlArray("B")]
[XmlArrayItem("B1", typeof(string))]
public List<string> B { get { return b1; } }
private readonly List<string> b1 = new List<string>();

以及:

var a = new A {
    A1 = {
        new A1 { B = { "a1.1", "a1.2" } },
        new A1 { B = { "a1.3", "a1.4" } }
    }
};

注意:删除默认命名空间别名声明:

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serial.Serialize(memory, objectToSerialize, ns);

然后输出:

<?xml version="1.0"?>
<A>
  <A1>
    <B>
      <B1>a1.1</B1>
      <B1>a1.2</B1>
    </B>
  </A1>
  <A1>
    <B>
      <B1>a1.3</B1>
      <B1>a1.4</B1>
    </B>
  </A1>
</A>