将XML字符串反序列化为复杂类型 [英] Deserialize XML string to complex type
问题描述
我的Xml(我无法更改):
My Xml (which I can't change):
<result>
<type>MAZDA</type>
<make>RX-8</type>
<country>JAPAN</country>
</result>
我的模型:
[Serializable, XmlRoot("result")]
public class VehicleDetails
{
public string Type { get; set; }
public string Make { get; set; }
public string Country { get; set; }
}
反序列化此XML的工作符合预期,但我想更改 Country
属性转换为复杂类型,例如:
de-serializing this XML works as expected but I want to change the Country
property to a complex type, like so:
public Country Country { get; set; }
并在 Country中输入国家名称 JAPAN。名称
属性,有什么想法吗?
and put the country name, "JAPAN", in the Country.Name
property, any ideas?
推荐答案
您可以装饰 Name <您的
Country
类的/ code>属性和 [XmlText]
属性,例如:
You could decorate the Name
property of your Country
class with the [XmlText]
attribute like this:
[XmlRoot("result")]
public class VehicleDetails
{
public string Type { get; set; }
public string Make { get; set; }
public Country Country { get; set; }
}
public class Country
{
[XmlText]
public string Name { get; set; }
}
还要注意,我已经摆脱了 [可序列化]
属性。它对XML序列化没有用。此属性用于二进制/远程序列化。
Also notice that I have gotten rid of the [Serializable]
attribute. It is useless for XML serialization. This attribute is used for binary/remoting serialization.
这是一个完整的示例,将按预期打印 JAPAN
:
And here's a full example that will print JAPAN
as expected:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
[XmlRoot("result")]
public class VehicleDetails
{
public string Type { get; set; }
public string Make { get; set; }
public Country Country { get; set; }
}
public class Country
{
[XmlText]
public string Name { get; set; }
}
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(VehicleDetails));
var xml =
@"<result>
<Type>MAZDA</Type>
<Make>RX-8</Make>
<Country>JAPAN</Country>
</result>";
using (var reader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(reader))
{
var result = (VehicleDetails)serializer.Deserialize(xmlReader);
Console.WriteLine(result.Country.Name);
}
}
}
这篇关于将XML字符串反序列化为复杂类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!