如何在C#中序列化对象数组?

时间:2013-10-24 04:10:48

标签: c# .net xml serialization

我使用xsd.exe和这个xml文件生成了一个c#类:

<?xml version="1.0" encoding="UTF-8"?>
<Mary>
    <Frank>
        <Joe>
            <Susan>
                <Stuff>data</Stuff>
            </Susan>
            <Susan>
                <Stuff>data</Stuff>
            </Susan>
        </Joe>
        <Joe>
            <Susan>
                <Stuff>data</Stuff>
            </Susan>
            <Susan>
                <Stuff>data</Stuff>
            </Susan>
        </Joe>
    </Frank>
</Mary>

The C# class that was generated can be viewed here.

我可以用数据初始化对象:

var susan = new MaryFrankJoeSusan(){Stuff = "my data"};
var frank = new MaryFrank(){Joe = new MaryFrankJoeSusan[1][]};
frank.Joe[0] = new MaryFrankJoeSusan[1]{susan};
var mary = new Mary { Items = new MaryFrank[1] { frank } };

我正在使用以下内容将其序列化为磁盘:

var serializer = new XmlSerializer(typeof(Mary));

using (Stream stream = new FileStream(@"C:\out.xml", FileMode.Create))
{
    var settings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = true, OmitXmlDeclaration = true};
    using (XmlWriter writer = new XmlTextWriter(stream, Encoding.Unicode))
    {
        serializer.Serialize(writer, mary);
        writer.Close();
    }
}

但是,初始化序列化程序时出现以下错误:

error CS0030: Cannot convert type 'MaryFrankJoeSusan[]' to 'MaryFrankJoeSusan'

如何将整个Mary对象序列化为磁盘?

1 个答案:

答案 0 :(得分:2)

那些生成的类已经关闭了。

问题正在发生,因为MaryFrank.Joe被声明为MaryFrankJoeSusan个对象的二维数组,但是它被XmlArrayItemAttribute修饰,告诉序列化程序每个项目2D阵列当然是MaryFrankJoeSusan类型MaryFrankJoeSusan[]

如果在生成的类中更改此行:

[System.Xml.Serialization.XmlArrayItemAttribute("Susan", typeof(MaryFrankJoeSusan),
 Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]

到此:

[System.Xml.Serialization.XmlArrayItemAttribute("Susan", typeof(MaryFrankJoeSusan[]),
 Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]

然后它将序列化而不会出错。但是,您无法获得所需的结果。而不是:

<Mary>
    <Frank>
        <Joe>
            <Susan>
                <Stuff>my data</Stuff>
            </Susan>
        </Joe>
    </Frank>
</Mary>

你会得到这个(注意额外的MaryFrankJoeSusan标签):

<Mary>
    <Frank>
        <Joe>
            <Susan>
                <MaryFrankJoeSusan>
                    <Stuff>my data</Stuff>
                </MaryFrankJoeSusan>
            </Susan>
        </Joe>
    </Frank>
</Mary>

真正的问题似乎是xsd.exe工具开始时错误地生成了类结构。它并不是在heirarchy中创建一个代表Joe的类,而是试图将Joe和Susan组合在一起,这在这里并没有真正起作用。

我通过该工具从问题中运行原始XML以生成XSD架构,我得到了这个:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Mary" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="Mary" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Frank">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Joe" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="Susan" minOccurs="0" maxOccurs="unbounded">
                      <xs:complexType>
                        <xs:sequence>
                          <xs:element name="Stuff" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

对我来说很好看。然后我采用相同的模式并再次运行该工具以生成C#类。我原本希望得到类似的东西:

[Serializable]
[XmlRoot(Namespace = "", ElementName = "Mary")]
public class Mary
{
    [XmlElement("Frank")]
    public Frank[] Frank { get; set; }
}
[Serializable]
public class Frank
{
    [XmlElement("Joe")]
    public Joe[] Joe { get; set; }
}
[Serializable]
public class Joe
{
    [XmlElement("Susan")]
    public Susan[] Susan { get; set; }
}
[Serializable]
public class Susan
{
    [XmlElement("Stuff")]
    public string Stuff { get; set; }
}

但是我得到了你在问题中链接的相同的破解类。所以它看起来像xsd工具中的一个bug给我。

要使其工作,您可以使用我上面创建的手工编写的类,将初始化代码更改为:

var susan = new Susan { Stuff = "my data" };
var joe = new Joe { Susan = new Susan[] { susan } };
var frank = new Frank { Joe = new Joe[] { joe } };
var mary = new Mary { Frank = new Frank[] { frank } };

- 或 -

另一种选择是改变xsd。将xs:sequenceFrank元素的Joe指标替换为xs:choice,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Mary" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="Mary" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Frank">
          <xs:complexType>
            <xs:choice> <!-- was xs:sequence -->
              <xs:element name="Joe" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                  <xs:choice> <!-- was xs:sequence -->
                    <xs:element name="Susan" minOccurs="0" maxOccurs="unbounded">
                      <xs:complexType>
                        <xs:sequence>
                          <xs:element name="Stuff" type="xs:string" minOccurs="0" />
                        </xs:sequence>
                      </xs:complexType>
                    </xs:element>
                  </xs:choice> <!-- was /xs:sequence -->
                </xs:complexType>
              </xs:element>
            </xs:choice> <!-- was /xs:sequence -->
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

使用此模式,生成的类更好:现在有一个类来表示Joe。 (我在这里简化了生成的代码并删除了一些简洁的属性):

[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Mary {
    [System.Xml.Serialization.XmlElementAttribute("Frank", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public MaryFrank[] Items { get; set; }
}

[System.SerializableAttribute()]
public partial class MaryFrank {
    [System.Xml.Serialization.XmlElementAttribute("Joe", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public MaryFrankJoe[] Items { get; set; }
}

[System.SerializableAttribute()]
public partial class MaryFrankJoe {
    [System.Xml.Serialization.XmlElementAttribute("Susan", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public MaryFrankJoeSusan[] Items { get; set; }
}

[System.SerializableAttribute()]
public partial class MaryFrankJoeSusan {
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Stuff { get; set; }
}

然后设置代码变为:

var susan = new MaryFrankJoeSusan() { Stuff = "my data" };
var joe = new MaryFrankJoe() { Items = new MaryFrankJoeSusan[] { susan } };
var frank = new MaryFrank() { Items = new MaryFrankJoe[] { joe } };
var mary = new Mary { Items = new MaryFrank[] { frank } };

我们得到预期的输出:

<?xml version="1.0" encoding="utf-16"?>
<Mary xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Frank>
        <Joe>
            <Susan>
                <Stuff>my data</Stuff>
            </Susan>
        </Joe>
    </Frank>
</Mary>