C#忽略xml反序列化中的父节点

时间:2016-04-09 23:33:39

标签: c# xml-parsing xml-deserialization

这是我在这里的第一篇文章,你可以想象,我只是c#的初学者。所以这是我的问题: 我将给定的xml反序列化为XmlSerializer的自定义类。

XML:

<epg>
<program start="20160404234500" stop="20160405001000" channel="281479340566592">
    <eventid>604042345</eventid>
    <titles>
        <title>Schlauberger - Quizzen, was Spaß macht! (1)</title>
    </titles>
    <events>
        <event>27. Schlauberger - Quizzen, was Spaß macht!</event>
    </events>
    <descriptions>
        <description>27. Schlauberger - Quizzen, was Spaß macht!</description>
    </descriptions>
</program>
<program start="20160504234500" stop="20160505001000" channel="281479340566587">
    <eventid>604042348</eventid>
    <title>Schlauberger - Quizzen, was Spaß macht! (2)</title>
    <event>28. Schlauberger - Quizzen, was Spaß macht!</event>
    <description>28. Schlauberger - Quizzen, was Spaß macht!</description>
</program>

自定义C#类:

public class Titles
{
    [XmlElement("title")]
    public string Title { get; set; }
}

public class SubTitles
{
    [XmlElement("event")]
    public string SubTitle { get; set; }
}

public class Descriptions
{
    [XmlElement("description")]
    public string Description { get; set; }
}

public class Program
{
    [XmlElement("eventid")]
    public string EventID { get; set; }
    [XmlElement("titles")]
    public Titles Titles { get; set; }
    [XmlElement("events")]
    public SubTitles SubTitles { get; set; }
    [XmlElement("descriptions")]
    public Descriptions Descriptions { get; set; }
    [XmlAttribute("start")]
    public string Start { get; set; }
    [XmlAttribute("stop")]
    public string Stop { get; set; }
    [XmlAttribute("channel")]
    public string Channel { get; set; }
    [XmlElement("title")]
    public string Title { get; set; }
    [XmlElement("event")]
    public string SubTitle { get; set; }
    [XmlElement("description")]
    public string Description { get; set; }
}

[XmlRoot(ElementName = "epg"), XmlType("epg")]
public class epg
{
    [XmlElement("program")]
    public List<Program> Program { get; set; }
}

到目前为止没问题。但正如你所看到的那样,因为&#34; title&#34;,&#34; event&#34;和&#34;描述&#34;有时嵌套在多数,有时不嵌套,我可以有时通过列表访问我的后期代码中的属性,有时直接访问。这使代码真的很不方便 那么在某种程度上可以忽略多数并且总是使用单个节点吗?

1 个答案:

答案 0 :(得分:1)

您可以向gem 'aws-sdk', '< 2.0' 类添加一些辅助函数(或属性),例如:

Program