XML - 如何在单个节点而不是整个文档中获取子节点? [英] XML - How to grab child nodes in single node and not whole document?

查看:33
本文介绍了XML - 如何在单个节点而不是整个文档中获取子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一直在四处寻找答案却找不到任何东西 - 我很新,所以也许我没有找到正确的关键词?

Been looking around for an answer and cant find anything - Im quite new so maybe Im not hitting up the right key words?

这是我正在使用的 XML 示例

This is a sample of the XML I am working with

<database>
<book>
<title>A</title>
<author>
  <name>1</name>
</author>
</book>
<book>
<title>B</title>
<author>
  <name>2</name>
</author>
<author>
  <name>3</name>
</author>
<author>
  <name>4</name>
</author>
<author>
  <name>5</name>
</author>
</book>
</database>

我正在尝试使用 C# XMLDocument 来抓取书籍 A author 1 和书籍 B author 1, 2, 3, 4, 5

Im trying to use C# XMLDocument to grab for book A author 1 and then for book B author 1, 2, 3, 4, 5

到目前为止,我正在使用的代码循环遍历所有作者,所以我得到了 A author 1, 2, 3, 4, 5 的书

So far the code I am working with is cycling through ALL the authors so I am getting book A author 1, 2, 3, 4, 5

我目前的代码大致如下

XmlDocument doc = new XmlDocument();
doc.Load("myxmlfile");
XmlNode root = doc.SelectSingleNode("database");
XmlNodeList nodelist = root.SelectNodes("book");

foreach (XmlNode n in nodelist)
        {

XmlNodeList authors = root.SelectNodes(".//author");
book.authorstring = "";
foreach (XmlNode author in authors)
       {
       book.authorstring = book.authorstring+author.SelectSingleNode("name").InnerText + ", ";
       }
}

如果我在//"之前使用.",我会读到一些地方,它会锚定"到当前节点,但它似乎没有工作,并且正在循环遍历所有节点

I read some where that if I use " . " before the " // " that it would "anchor" to the current node but it doesnt seem to be working and is cycling through all the nodes

我做错了什么或遗漏了什么?

What am I doing wrong or missing?

推荐答案

如果我理解正确,您的错误就在这一行:

If i understand you correctly your error is in this line :

XmlNodeList authors = root.SelectNodes(".//author");

应该是

XmlNodeList authors = n.SelectNodes(".//author");

这篇关于XML - 如何在单个节点而不是整个文档中获取子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆