且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将XML字符串反序列化为复杂类型

更新时间:2022-02-28 00:54:50

您可以装饰 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);
        }
    }
}