使用XML类属性,如何用内部文本和属性表示XML标记?

Jef*_*ley 14 c# xml xml-serialization

假设我有这个XML文件:

<weather>
   <temp>24.0</temp>
   <current-condition iconUrl="http://....">Sunny</current-condition>
</weather>
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用Attributes创建一个C#类来表示它,以便调用XmlSerializer并具有强类型标记访问权限.我认为结构看起来像这样:

[XmlRoot("weather")]
public class WeatherData
{
    [XmlElement("temp")]
    public string Temp { get; set; }

    [XmlElement("current-condition")]
    public CurrentCondition currentCond = new CurrentCondition();
}

public class CurrentCondition
{
    [XmlAttribute("iconUrl")
    public string IconUrl { get; set; }

    // Representation of Inner Text?
}
Run Code Online (Sandbox Code Playgroud)

代表'temp'标签是直截了当的.但是,给定像current-condition这样既有内部文本又有属性的标记,我该如何表示内部文本?

我可能过于复杂了,所以请随意提出替代方案.

Joh*_*ers 25

使用[XmlText]描述内部文本内容.

public class CurrentCondition
{
    [XmlAttribute("iconUrl")
    public string IconUrl { get; set; }

    // Representation of Inner Text:
    [XmlText]
    public string ConditionValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)