2

我想将 xml 字符串序列化为对象集合,但我只能获取第一个对象。如果我在 xml 中添加更多对象,则会出错。不知道我错过了什么。我尝试将类型声明为 Emp[]

这是我的两个“Emp”xml 字符串

string empsworking = "<?xml version='1.0' encoding='utf-8'?><Emp><EmpInfo><Code>vv</Code><FirstName>van</FirstName><LastName>sa</LastName><Destination>sc</Destination></EmpInfo><EmpInfo><Code>rr</Code><FirstName>ro</FirstName><LastName>sa</LastName><Destination>ph</Destination></EmpInfo></Emp>";

         string empsNotworking = "<?xml version='1.0' encoding='utf-8'?><Emp><EmpInfo><Code>vv</Code><FirstName>van</FirstName><LastName>sa</LastName><Destination>sc</Destination></EmpInfo></Emp>";

我的课看起来像

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class Emp
{
    /// <remarks/>
   public EmpInfo EmpInfo { get; set; }
    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }

}

/// <remarks/>
[XmlRoot(ElementName = "EmpInfo")] 
public class EmpInfo
{

    /// <remarks/>
    public string Code;

    /// <remarks/>
    public string FirstName;

    /// <remarks/>
    public string LastName;

    /// <remarks/>
    public string Destination;
}

我的序列化代码是

           StringReader stream = null;
       XmlTextReader reader = null;
        Emp empprofile;
       try
       {
           // serialise to object
           XmlSerializer serializer = new XmlSerializer(typeof(Emp));
           stream = new StringReader(emps); // read xml data
           reader = new XmlTextReader(stream);  // create reader
           // covert reader to object
           empprofile = (Emp)serializer.Deserialize(reader);
       }
       catch
       {
           return null;
       }
       finally
       {
           if (stream != null) stream.Close();
           if (reader != null) reader.Close();
       }

我只能通过 empworking 读取/获取对象。如何将其作为“EmpInfo”的集合?请指导!

4

1 回答 1

1

试试这样:

[TestFixture]
public class SerializeTest
{
    [Test]
    public void SerializeEmpTest()
    {
        EmpCollection empCollection = new EmpCollection()
            {
                new EmpInfo() {Code = "1", FirstName = "Anita"}, 
                new EmpInfo() {Code = "1", FirstName = "Johan"}
            };
        string xmlString = empCollection.GetXmlString();
    }
}

[XmlType, XmlRoot]
public class EmpCollection : List<EmpInfo>
{

}

[XmlType]
public class EmpInfo
{
    public string Code;

    public string FirstName;

}

public static class Extenstion
{
    public static string GetXmlString<T>(this T objectToSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
        StringBuilder stringBuilder = new StringBuilder();
        string xml;
        using (var xmlTextWriter = new XmlTextWriter(new StringWriter(stringBuilder)))
        {
            xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);
            xml = stringBuilder.ToString();
        }
        return xml;
    }
}
于 2012-10-21T12:45:38.870 回答