如何将此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>
感谢您提前提出的建议!
答案 0 :(得分:2)
你必须为Adress创建不同的类, 或实现IXmlSerializable
并放置您自己的方法来拆分地址字符串(使用[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?
如果你真的想要
,有两种方法要将Address
保留为string
,Person
课程必须按照 @interneo 的说法实施IXmlSerializable
,但要自行序列化很难且容易出错。
更清洁的解决方案是将Address
的类型更改为同时实现IXmlSerializable
的类型。我的示例
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主类你也会得到子类的实例。