【发布时间】:2019-12-17 17:52:44
【问题描述】:
我目前正在尝试解析 som XML 数据,我无法显示整个文档,因为它包含很多敏感信息,所以我只能提供一个 sn-p。
这就是我解析我的 xml 的方式
XmlSerializer serializer = new XmlSerializer(typeof(Rss));
XmlTextReader reader = new XmlTextReader("urlToData");
var k = serializer.Deserialize(reader);
正如我所说,我无法提供实际的 URL,所以我在这里粘贴了一些测试数据。 https://hatebin.com/pspnhpihlz
无论如何,当我查看 k 以查看它的内容时,第一个 Description 包含数据,但是当我开始深入研究它时,例如 Items -> 并选择一个项目并查看Descriptionsrc和p为null,不知道为什么,明显有数据。
这是我使用 XML2C# 生成器时生成的对象
[XmlRoot(ElementName = "img")]
public class Img
{
[XmlAttribute(AttributeName = "src")]
public string Src { get; set; }
[XmlAttribute(AttributeName = "alt")]
public string Alt { get; set; }
}
[XmlRoot(ElementName = "description")]
public class Description
{
[XmlElement(ElementName = "img")]
public Img Img { get; set; }
[XmlElement(ElementName = "p")]
public string P { get; set; }
}
[XmlRoot(ElementName = "item")]
public class Item
{
[XmlElement(ElementName = "link")]
public string Link { get; set; }
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "author")]
public string Author { get; set; }
[XmlElement(ElementName = "pubDate")]
public string PubDate { get; set; }
[XmlElement(ElementName = "description")]
public Description Description { get; set; }
[XmlElement(ElementName = "category")]
public string Category { get; set; }
}
[XmlRoot(ElementName = "channel")]
public class Channel
{
[XmlElement(ElementName = "link")]
public string Link { get; set; }
[XmlElement(ElementName = "title")]
public string Title { get; set; }
[XmlElement(ElementName = "description")]
public string Description { get; set; }
[XmlElement(ElementName = "pubDate")]
public string PubDate { get; set; }
[XmlElement(ElementName = "generator")]
public string Generator { get; set; }
[XmlElement(ElementName = "copyright")]
public string Copyright { get; set; }
[XmlElement(ElementName = "lastBuildDate")]
public string LastBuildDate { get; set; }
[XmlElement(ElementName = "language")]
public string Language { get; set; }
[XmlElement(ElementName = "item")]
public List<Item> Item { get; set; }
}
[XmlRoot(ElementName = "rss")]
public class Rss
{
[XmlElement(ElementName = "channel")]
public Channel Channel { get; set; }
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
}
正如我所说,它可以很好地解析数据,只是在Items 内部,每个Item 在其src 和p 属性中都有一个null 描述,我不知道为什么。
这是为什么呢?
【问题讨论】:
-
您的示例文件末尾的
<item><link太多了。当我删除它时,代码按预期工作。请提供显示问题的minimal reproducible example。 -
如果这是标准的 rss 提要,您可以使用already invented wheel
-
@NineBerry 我会将 url 发布到 XML 数据,但它包含敏感数据,所以我不知道该怎么做。
-
@RileyVarga 使用产生问题的随机数据构建一个工作示例 xml 文件。
-
当你这样做的时候,你检查了
Items集合吗?每个项目都有一个Description,但其中的两个属性Img和p为空