C#XML序列化和放大器;反序列化 [英] C# Xml Serialization & Deserialization

查看:131
本文介绍了C#XML序列化和放大器;反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将对象序列化和放大器;保存到一个SQL Server 2008中的XML领域。我也有一些反序列化code,它重新水合物的对象。我能够序列化和放大器;保存对象到数据库,却得到了一个根元素缺少异常。

  [XmlRoot(病人)]
公共类PatientXml
{
    私人AddressXml _address = NULL;
    私人EmergencyContactXml _emergencyContact = NULL;
    私人PersonalXml _personal = NULL;    [的XmlElement]
    公共PersonalXml个人
    {
        {返回_personal; }
        集合{_personal =价值; }
    }    [的XmlElement]
    公共AddressXml地址
    {
        {返回_address; }
        集合{_address =价值; }
    }    [的XmlElement]
    公共EmergencyContactXml EmergencyContact
    {
        {返回_emergencyContact; }
        集合{_emergencyContact =价值; }
    }    公共PatientXml(){}
    公共PatientXml(病人病人)
    {
        _address =新AddressXml(patient.Address);
        _emergencyContact =新EmergencyContactXml(patient.EmergencyInfo);
        _personal =新PersonalXml(患者);
    }
}公共类PersonalXml
{
    民营字符串_FirstName =的String.Empty,_lastName =的String.Empty,_dateOfBirth =的String.Empty,_phone =的String.Empty;    [XmlAttribute]
    公共字符串名字
    {
        {返回_FirstName; }
        集合{_FirstName =价值; }
    }    [XmlAttribute]
    公共字符串姓氏
    {
        {返回_lastName; }
        集合{_lastName =价值; }
    }    [XmlAttribute]
    公共字符串DATEOFBIRTH
    {
        {返回_dateOfBirth; }
        集合{_dateOfBirth =价值; }
    }    [XmlAttribute]
    公共字符串电话
    {
        {返回_phone; }
        集合{_phone =价值; }
    }    公共PersonalXml(){}
    公共PersonalXml(病人患者)
    {
        _FirstName = patient.FirstName;
        _lastName = patient.LastName;
        _dateOfBirth = patient.DateOfBirth.ToShortDateString();
        _phone = patient.Phone;
    }
}公共类AddressXml
{
    私人字符串_address1 =的String.Empty,_address2 =的String.Empty,_City =的String.Empty,_state =的String.Empty,_zip =的String.Empty;    [XmlAttribute]
    公共字符串地址1
    {
        {返回_address1; }
        集合{_address1 =价值; }
    }    [XmlAttribute]
    公共字符串地址2
    {
        {返回_address2; }
        集合{_address2 =价值; }
    }    [XmlAttribute]
    公共字符串城
    {
        {返回_City; }
        集合{_City =价值; }
    }    [XmlAttribute]
    公共字符串状态
    {
        {返回_state; }
        集合{_state =价值; }
    }    [XmlAttribute]
    公共字符串邮编
    {
        {返回_zip; }
        集合{_zip =价值; }
    }    公共AddressXml(){}
    公共AddressXml(地址地址)
    {
        _address1 = address.Address1;
        _address2 = address.Address2;
        _City = address.City;
        _state = address.State,
        _zip = address.Zip code;
    }
}公共类EmergencyContactXml
{
    私人字符串_name =的String.Empty,_phone =的String.Empty,_relationship =的String.Empty;    [XmlAttribute]
    公共字符串名称
    {
        {返回_name; }
        集合{_name =价值; }
    }    [XmlAttribute]
    公共字符串电话
    {
        {返回_phone; }
        集合{_phone =价值; }
    }    [XmlAttribute]
    公共字符串关系
    {
        {返回_relationship; }
        集合{_relationship =价值; }
    }    公共EmergencyContactXml(){}
    公共EmergencyContactXml(EmergencyContact触点)
    {
        _name = contact.ContactName;
        _phone = contact.Phone;
        _relationship = contact.Relationship;
    }
}

序列化的XML输出​​:

 <患者
    XMLNS:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance
    的xmlns:XSD =htt​​p://www.w3.org/2001/XMLSchema>
    <个人名字=测试姓氏=用户1DATEOFBIRTH =1966年3月13日手机=6304449866/>
    <地址地址1 =123有些ST城市=巴特利特状态=CTZIP =60111/>
    < EmergencyContact NAME =Chanduwarthana博士手机=6309769484的关系=父亲/>
< /病人GT;

&Serization放大器;反序列化code:

 公共静态类的XmlSerializer
{
    公共静态字符串序列化< T>(T项)
    {
        MemoryStream的memStream =新的MemoryStream();
        使用(XmlTextWriter的的TextWriter =新的XmlTextWriter(memStream,Encoding.Uni code)条)
        {
            System.Xml.Serialization.XmlSerializer串=新System.Xml.Serialization.XmlSerializer(typeof运算(T));
            serializer.Serialize(的TextWriter,项目);            memStream = textWriter.BaseStream为MemoryStream的;
        }
        如果(memStream!= NULL)
            返回Encoding.Uni code.GetString(memStream.ToArray());
        其他
            返回null;
    }    公共静态ŧ反序列化< T>(字符串的xmlString)
    {
        如果(string.IsNullOrWhiteSpace(的xmlString))
            返回默认(T);        使用(MemoryStream的memStream =新的MemoryStream())
        {
            使用(XmlTextWriter的的TextWriter =新的XmlTextWriter(memStream,Encoding.Uni code)条)
            {
                memStream.Position = 0;
                System.Xml.Serialization.XmlSerializer串行=新System.Xml.Serialization.XmlSerializer(typeof运算(T));
                回报(T)serializer.Deserialize(memStream);
            }
        }
    }
}


解决方案

在您的反序列化code你要创建一个MemoryStream和XmlTextWriter的,但你不给它反序列化字符串。

 使用(MemoryStream的memStream =新的MemoryStream())
{
    使用(XmlTextWriter的的TextWriter =新的XmlTextWriter(memStream,Encoding.Uni code)条)
    {
        //略
    }
}

您可以通过字节内存流,并与XmlTextWriter的干脆做掉。

 使用(MemoryStream的memStream =新的MemoryStream(Encoding.Uni code.GetBytes(的xmlString)))
{
    System.Xml.Serialization.XmlSerializer串行=新System.Xml.Serialization.XmlSerializer(typeof运算(T));
    回报(T)serializer.Deserialize(memStream);
}

I am trying to serialize an object & save it into a Sql server 2008 xml field. I also have some deserialization code that re-hydrates the object. I am able to serialize & save the object into the db, but get a "Root element missing" exception.

[XmlRoot("Patient")]
public class PatientXml
{
    private AddressXml _address = null;
    private EmergencyContactXml _emergencyContact = null;
    private PersonalXml _personal = null;

    [XmlElement]
    public PersonalXml Personal
    {
        get { return _personal; }
        set { _personal = value; }
    }

    [XmlElement]
    public AddressXml Address
    {
        get { return _address; }
        set { _address = value; }
    }

    [XmlElement]
    public EmergencyContactXml EmergencyContact
    {
        get { return _emergencyContact; }
        set { _emergencyContact = value; }
    }

    public PatientXml(){}
    public PatientXml(Patient patient)
    {
        _address = new AddressXml(patient.Address);
        _emergencyContact = new EmergencyContactXml(patient.EmergencyInfo);
        _personal = new PersonalXml(patient);
    }
}

public class PersonalXml
{
    private string _firstName = string.Empty, _lastName = string.Empty, _dateOfBirth = string.Empty, _phone = string.Empty;

    [XmlAttribute]
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    [XmlAttribute]
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    [XmlAttribute]
    public string DateOfBirth
    {
        get { return _dateOfBirth; }
        set { _dateOfBirth = value; }
    }

    [XmlAttribute]
    public string Phone
    {
        get { return _phone; }
        set { _phone = value; }
    }

    public PersonalXml(){}
    public PersonalXml(Patient patient)
    {
        _firstName = patient.FirstName;
        _lastName = patient.LastName;
        _dateOfBirth = patient.DateOfBirth.ToShortDateString();
        _phone = patient.Phone;
    }
}

public class AddressXml
{
    private string _address1 = string.Empty, _address2 = string.Empty, _city = string.Empty, _state = string.Empty, _zip = string.Empty;

    [XmlAttribute]
    public string Address1
    {
        get { return _address1; }
        set { _address1 = value; }
    }

    [XmlAttribute]
    public string Address2
    {
        get { return _address2; }
        set { _address2 = value; }
    }

    [XmlAttribute]
    public string City
    {
        get { return _city; }
        set { _city = value; }
    }

    [XmlAttribute]
    public string State
    {
        get { return _state; }
        set { _state = value; }
    }

    [XmlAttribute]
    public string Zip
    {
        get { return _zip; }
        set { _zip = value; }
    }

    public AddressXml(){}
    public AddressXml(Address address)
    {
        _address1 = address.Address1;
        _address2 = address.Address2;
        _city = address.City;
        _state = address.State;
        _zip = address.ZipCode;
    }
}

public class EmergencyContactXml
{
    private string _name = string.Empty, _phone = string.Empty, _relationship = string.Empty;

    [XmlAttribute]
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    [XmlAttribute]
    public string Phone
    {
        get { return _phone; }
        set { _phone = value; }
    }

    [XmlAttribute]
    public string Relationship
    {
        get { return _relationship; }
        set { _relationship = value; }
    }

    public EmergencyContactXml(){}
    public EmergencyContactXml(EmergencyContact contact)
    {
        _name = contact.ContactName;
        _phone = contact.Phone;
        _relationship = contact.Relationship;
    }
}

Serialized Xml output:

<Patient 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Personal FirstName="Test" LastName="User 1" DateOfBirth="3/13/1966" Phone="6304449866" />
    <Address Address1="123 Some St" City="Bartlett" State="CT" Zip="60111" />
    <EmergencyContact Name="Dr Chanduwarthana" Phone="6309769484" Relationship="Father" />
</Patient>

Serization & Deserialization code:

public static class XmlSerializer
{
    public static string Serialize<T>(T item)
    {
        MemoryStream memStream = new MemoryStream();
        using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            serializer.Serialize(textWriter, item);

            memStream = textWriter.BaseStream as MemoryStream;
        }
        if (memStream != null)
            return Encoding.Unicode.GetString(memStream.ToArray());
        else
            return null;
    }

    public static T Deserialize<T>(string xmlString)
    {
        if (string.IsNullOrWhiteSpace(xmlString))
            return default(T);

        using (MemoryStream memStream = new MemoryStream())
        {
            using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
            {
                memStream.Position = 0;
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(memStream);
            }
        }
    }
}

解决方案

In your deserialization code you're creating a MemoryStream and XmlTextWriter but you're not giving it the string to deserialize.

using (MemoryStream memStream = new MemoryStream())
{
    using (XmlTextWriter textWriter = new XmlTextWriter(memStream, Encoding.Unicode))
    {
        // Omitted
    }
}

You can pass the bytes to the memory stream and do away with the XmlTextWriter altogether.

using (MemoryStream memStream = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    return (T)serializer.Deserialize(memStream);
}

这篇关于C#XML序列化和放大器;反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆