问题描述
如何查询属于元素节点的所有XML节点?
我想查询所有book标记的same_books标记下的数据,但是我仅获得第一本book标记数据。 XML响应的URL为https://www.goodreads.com/book/title.xml?key=Uxb0zPb86N4STVy2ECWYA&title=DUNE
结构是这样的:
<GoodreadsResponse>
<Request>
<book>
<Similar_books>
<book>
</book>
<book>
</book>
<book>
</book>
<book>
</book>
</Similar_books>
<book>
<Request>
</GoodreadsResponse>
我的代码看起来像这样。
search.Text = "";
var xdoc= XDocument.Load("https://www.goodreads.com/book/title.xml?key=Uxb0zPb86N4STVy2ECWYA&title=" + title.Text);
var S = xdoc.XPathSelectElements("//similar_books");
var b = xdoc.XPathSelectElements("//book");
XElement search_result =
( from xFi in S.Elements()
select xFi).FirstorDefault();
if (search_result != null)
{
BOOK_URL.source = ImageSource.FromUri(new Uri(search_result.Element("image_url").Value));
search.Text =
"Title: " + search_result.Element("title").Value + "\n"+ "Average ratings: " + search_result.Element("average_rating").Value + "\n" +
"ISBN: " + search_result.Element("isbn").Value + "\n" +
"PUBLICATION YEAR: " + search_result.Element("publication_year").Value + "\n";
}
else
{
search.Text = "Found nothing";
}
解决方法
此XPath表达式对我有用
/GoodreadsResponse/book/similar_books/book
请注意,原始帖子中的“示例” XML与ACTUAL XML的结构不同,这可能就是为什么我之前的响应无法正常工作的原因。
- “类似书”,而不是“类似书”
- “请求”不是“ books”的父节点,而是同级