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

本文关键字:错误 xml 出错 对象 序列化 | 更新日期: 2023-09-27 18:04:10

在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>
我的班级是这样的交流
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中:

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);  
        }
    }
}

一个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" /> 

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

是的,这是正确的…伊什。它没有显示更多的原因是因为您的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>