使用XML类属性,如何表示既有内部文本又有属性的XML标记?

16

假设我有这个XML文件:

<weather>
   <temp>24.0</temp>
   <current-condition iconUrl="http://....">Sunny</current-condition>
</weather>

我试图使用属性(Attribute)创建一个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?
}

处理'temp'标签很简单。然而,如果有一个像current-condition这样既有内部文本又有属性的标签,如何表示内部文本呢?

我可能过于复杂化了这个问题,因此请随意提出其他建议。

1个回答

30

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

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

    // Representation of Inner Text:
    [XmlText]
    public string ConditionValue { get; set; }
}

我在浏览 MSDN 时看到过这个问题,这证明我肯定没有仔细阅读它!谢谢! - Jeff Dalley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接