字符串到对象的XML序列化。 Object包含可以填充String的Property

时间:2014-01-15 10:19:16

标签: c# .net xml serialization xml-serialization

如何将此XML字符串序列化为对象?

给定XML定义:

<Person>
    <Name>Jack</Name>
    <Address><Hotel>Merriot</Hotel></Address>
</Person>

给定对象定义:

Public Class Person
{
    Public String Name;
    Public String Address;
}

所以,基本上在序列化之后,我会将Person对象的Name属性值设为“Jack”,而Address Property的值为<Hotel>Merriot</Hotel>

感谢您提前提出的建议!

4 个答案:

答案 0 :(得分:2)

你必须为Adress创建不同的类, 或实现IXmlSerializable

http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable%28v=vs.110%29.aspx#fbid=FpiOK3ZYdUD

并放置您自己的方法来拆分地址字符串(使用[XmlIgnore]作为当前地址)

答案 1 :(得分:1)

public class Person
{
    public string Name {get;set;}
    public Address Address {get;set;}
}

public class Address
{
   public string Hotel{get;set;}
}

答案 2 :(得分:1)

为什么要原始XML?

如果你真的想要

,有两种方法
  1. 要将Address保留为stringPerson课程必须按照 @interneo 的说法实施IXmlSerializable,但要自行序列化很难且容易出错。

  2. 更清洁的解决方案是将Address的类型更改为同时实现IXmlSerializable的类型。我的示例

  3. 中的该类型为InnerXml

    样品:

    public class Person
    {
        public string Name { get; set; }
        public InnerXml Address { get; set; }
    }
    
    public class InnerXml : IXmlSerializable
    {
        public string Content { get; set; }
    
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }
    
        public void ReadXml(System.Xml.XmlReader reader)
        {
            Content = reader.ReadInnerXml();
        }
    
        public void WriteXml(System.Xml.XmlWriter writer)
        {
            if (Content != null)
            {
                writer.WriteRaw(Content);
            }
        }
    }
    
    using (var testXmlReader = new StringReader(testXml))
    {
        var serializer = new XmlSerializer(typeof(Person));
        var person = (Person)serializer.Deserialize(testXmlReader);
    
        Console.WriteLine(person.Address.Content); //outputs <Hotel>Merriot</Hotel>
    }
    

答案 3 :(得分:0)

here the case is of nested Serializaton:
Better use following approach:

[Serializable]
public class person
{
public String Name;
public Address HotelAddress;
}

[Serializable ]
public class Address 
 {
  public string HotelName;
 }

现在deserlize主类你也会得到子类的实例。