我有一个客户会发送一个XML数据源,我使用以下代码进行解析。这个代码是有效的。
reviews = from item in xmlDoc.Descendants("node")
select new ForewordReview()
{
PubDate = (string)item.Element("created"),
Isbn = (string)item.Element("isbn"),
Summary = (string)item.Element("review")
};
在获取所有“评论”后,我将IEnumerable强制转换为List并将其返回。最初,我很容易解析他们的XML,它看起来像这样:
<reviews>
<node>
<created>01-01-1900</created>
<ISBN>12345657890123</ISBN>
<Review>This is a nice and silly book</Review>
</node>
<node>
<created>01-01-2011</created>
<ISBN>1236245234554</ISBN>
<Review>This is a stupid book</Review>
</node>
<node>
<created>12-06-1942</created>
<ISBN>1234543234577</ISBN>
<Review>This is a old, naughty book</Review>
</node>
</reviews>
然而,他们更改了它们的模式,我无法访问,现在他们的XML在结尾添加了一个最终的<node>
标签,其中不包含我要查找的后代元素,因此我的解析在这个最后的标签上中断并抛出异常。下面是示例:
<reviews>
<node>
<created>01-01-1900</created>
<ISBN>12345657890123</ISBN>
<Review>This is a nice and silly book</Review>
</node>
<node>
<created>01-01-2011</created>
<ISBN>1236245234554</ISBN>
<Review>This is a stupid book</Review>
</node>
<node>
<created>12-06-1942</created>
<ISBN>1234543234577</ISBN>
<Review>This is a old, naughty book</Review>
</node>
<node>
<count>4656</count>
</node>
</reviews>
我需要知道是否有一种方法可以忽略这个最终标签(它总是出现在文档的末尾),即使它与我要查找的所有其他“节点”标签具有相同的名称。 我确实在此代码块周围使用了try-catch,但是如果它看到此错误,它不会返回good reviews列表。
谢谢大家。
where item.Element("count") == null
(或者反过来,"created" != null). - ordag