【发布时间】:2019-03-22 15:04:02
【问题描述】:
我有一个基本上如下所示的 XML 文档:
<Item>
<Seller>
<UserID>SomeSeller</UserID>
<FeedbackScore>2535</FeedbackScore>
</Seller>
</Item>
现在我正在尝试解析文档,如下所示:
var document = XDocument.Parse(upcList);
XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
var result= document
.Descendants(ns + "Item")
.Select(item => new CustomClass
{
FeedBackScore = Convert.ToInt32(item.Descendants(ns+ "Seller")
.Where(p=>p.Name.LocalName=="FeedbackScore").FirstOrDefault()),
Sales = (int) item.Element(ns+"QuantitySold"),
Location = (string)item.Element(ns+"Location"),
CurrentPrice = (double)item.Element(ns + "CurrentPrice"),
Title = (string)item.Element(ns + "Title"),
ItemID = (string)item.Element(ns + "ItemID")
}).ToList();
请注意这部分我如何尝试解析 FeedbackScore 节点值:
FeedBackScore = Convert.ToInt32(item.Descendants(ns+ "Seller")
.Where(p=>p.Name.LocalName=="FeedbackScore").FirstOrDefault()),
但是当我尝试解析它时,我将所有“FeedbackScore”节点值都设为“0”:(
谁能告诉我我做错了什么以及如何在这个节点“2535”中获取这个值?
【问题讨论】:
-
你试过
XNamespace ns = ""吗? -
所以,document.Descendants() 返回条目,对吗?只是那个会返回“0”吗?我说的对吗?
-
FirstOrDefault 返回什么类型?那不是 XElement 吗?你应该在哪个上面使用
Value属性? -
是的,那是因为转换。不确定“null”是否会转换为 0,但这是我的怀疑。但如果是这样,那就意味着找不到您的元素。
-
我猜通过调用
Descendants(ns+ "Seller")你会得到Seller节点,它们的名字永远不会匹配"FeedbackScore"并产生null。然后Convert.ToIn32(null)yields0。您应该直接使用Descendants()来查看“FeedBackScore”(类似item.Descendants("FeedBackValue").FirstOrDefault()的东西应该可以解决问题)。
标签: c# asp.net xml asp.net-mvc xml-parsing