【问题标题】:Explicitly retrieving contents of XML element as string以字符串形式显式检索 XML 元素的内容
【发布时间】:2012-11-20 17:19:28
【问题描述】:

我有这样的 XML:

<entry xmlns="http://www.w3.org/2005/Atom">
    <fullstoryimage>
        <img src="http://someimageurl/animage.jpg" width="220" height="150" border="0" />
    </fullstoryimage>
</entry>

还有这样的模型:

[Serializable]
[XmlRoot("entry", Namespace = "http://www.w3.org/2005/Atom")]
public class NewsItem
{
    [XmlElement("fullstoryimage")]
    public string Image { get; set; }
}

如何适当地标记“fullstoryimage”以将内容作为字符串提取?

注意:XML 不是我设计的,无法更改,无论它看起来多么愚蠢。

【问题讨论】:

    标签: c# xml serialization xml-serialization


    【解决方案1】:

    如果你想要获取图片链接,你可以使用 Linq2Xml

    XNamespace ns = "http://www.w3.org/2005/Atom";
    var imgLink = XDocument.Parse(xml)
                    .Descendants(ns + "img")
                    .Select(i => i.Attribute("src").Value)
                    .FirstOrDefault();
    

    【讨论】:

    • 理想情况下,我想要使用标记和反序列化器直接进入模型的东西。我在上面的示例中对其进行了很多简化,但是我还有很多其他属性以这种方式填充,为了保持一致性,我也希望“fullstoryimage”也是如此。如果证明不可能,我会使用你的方法,谢谢。
    【解决方案2】:

    为了保持我的序列化一致,我这样做了:

    public class StoryImage
    {
        [XmlElement("img")]
        public Image Img { get; set; }
    }
    
    public class Image
    {
        [XmlAttribute("src")]
        public string Source { get; set; }
    }
    
    [Serializable]
    [XmlRoot("entry", Namespace = "http://www.w3.org/2005/Atom")]
    public class NewsItem
    {
        [XmlElement("fullstoryimage")]
        public StoryImage FullStoryImage { get; set; }
    }
    

    然后可以通过 newsItem.FullStoryImage.Img.Source 访问 URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      • 2014-04-19
      • 2013-10-17
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多