.NET ODATA - XML Serializer - 反序列化嵌套对象

时间:2018-02-12 13:12:03

标签: c# asp.net .net .net-core

我有以下XML

<?xml version="1.0" encoding="UTF-8"?>
<feed xml:base="xxx" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns="http://www.w3.org/2005/Atom">
    <id>xxx</id>
    <title>xxx</title>
    <updated>2018-02-12T11:33:38.737Z</updated>
    <link href="xxx" rel="self" title="xxx"></link>
    <entry>
        <id>xxx</id>
        <category term="xxx" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"></category>
        <title></title>
        <updated>2018-02-11T22:04:10.990Z</updated>
        <content type="application/xml">
            <m:properties>
                <d:ID m:type="Edm.Int64">123456789</d:ID>
                <d:AutoNumber m:type="Edm.Int64">313800</d:AutoNumber>
            </m:properties>
        </content>
    </entry>
    <entry>
        <id>xxx</id>
        <category term="xxx" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"></category>
        <title></title>
        <updated>2018-02-11T22:04:10.990Z</updated>
        <content type="application/xml">
            <m:properties>
                <d:ID m:type="Edm.Int64">987654321</d:ID>
                <d:AutoNumber m:type="Edm.Int64">313800</d:AutoNumber>
            </m:properties>
        </content>
    </entry>
</feed>  

我想反序列化此XML并使用以下模型将数据存储在SQL Server上;

[XmlType(TypeName = "feed", Namespace = "http://www.w3.org/2005/Atom")]
public class Feed
{
    [XmlElement(ElementName = "title")]
    public string Title { get; set; }

    [XmlElement(ElementName = "updated")]
    public DateTime? Updated { get; set; }

    [XmlElement(ElementName = "id")]
    public string Id { get; set; }

    [XmlElement(ElementName = "entry")]
    public List<Entry> Entries { get; set; }

    public Feed()
    {
        Entries = new List<Entry>();
    }
}    

public class Entry
{
    [XmlElement(ElementName = "ID")]
    public long? ID { get; set; }

    [XmlElement(ElementName = "AutoNumber")]
    public long? AutoNumber{ get; set; }
}   

我使用以下方法;

public void LoadXml()
{

    XmlSerializer serializer = new XmlSerializer(typeof(Feed), "http://www.w3.org/2005/Atom");

    using (StreamReader sr = new StreamReader("myfile.xml"))
    {
        Feed readFeed = serializer.Deserialize(sr) as Feed;
        foreach(var entry in readFeed.Entries)
        {
            System.Console.WriteLine(entry.ID);
            System.Console.WriteLine(entry.AutoNumber);
        }
        Console.WriteLine(readFeed.Updated);                
    }
}   

Feed类被正确映射,条目类未正确映射,因为它位于&#34;内容类型&#34;和&#34; m:属性&#34;标签。如何将属性ID和自动编号映射到Entry Class?

0 个答案:

没有答案