反序列化时直接定位元素属性值

时间:2014-01-20 20:45:37

标签: c# xml deserialization

我有一个看起来大致如下的给定xml文件:

<InstanceID val="0" xmlns="urn:schemas-upnp-org:metadata-1-0/AVT/">
    <TransportState val="PLAYING" />
    <CurrentPlayMode val="SHUFFLE_NOREPEAT" />
    <CurrentCrossfadeMode val="0" />

    <!-- The actual xml has about 20 elements, 
         all elements have a val attribute. -->
</InstanceID>

我想要反序列化这个xml而不必为每个元素创建一个类。有没有办法直接读取每个元素的'val'属性? 此刻我有这样的课程:

[XmlRoot("InstanceID", Namespace = "urn:schemas-upnp-org:metadata-1-0/AVT/")]
class AVTransportEventData
{
    [XmlElement("TransportState")]
    public List<TransportState> TransportState { get; set; }

    [XmlElement("CurrentPlayMode")]
    public List<CurrentPlayMode> CurrentPlayMode { get; set; }

    [XmlElement("CurrentCrossfadeMode")]
    public CurrentCrossfadeMode CurrentCrossfadeMode { get; set; }
}

public class TransportState
{
    [XmlAttribute("val")]
    public string Value { get; set; }
}

public class CurrentPlayMode
{
    [XmlAttribute("val")]
    public string Value { get; set; }
}

public class CurrentCrossfadeMode
{
    [XmlAttribute("val")]
    public string Value { get; set; }
}

这很糟糕。它应该更像是这样的假代码:

[XmlRoot("InstanceID", Namespace = "urn:schemas-upnp-org:metadata-1-0/AVT/")]
class AVTransportEventData
{
    [XmlElement("TransportState"), [XmlAttribute("val")]
    public string TransportState { get; set; }

    [XmlElement("CurrentPlayMode"), [XmlAttribute("val")]
    public string CurrentPlayMode { get; set; }

    [XmlElement("CurrentCrossfadeMode"), [XmlAttribute("val")]
    public string CurrentCrossfadeMode { get; set; }
}

每个元素只会出现一次,我只需要'val'属性值。 这可能吗?或者它是否提供更多解决方案?

0 个答案:

没有答案