XML - How to grab child nodes in single node and not whole document?

≯℡__Kan透↙ 提交于 2019-12-11 03:29:33

问题


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

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>

Im trying to use C# XMLDocument to grab for book A author 1 and then for book B 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

The code I have so far is as follows roughly

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?


回答1:


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

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

it should be

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



回答2:


Use linq2XML..it is simple to use

XElement doc=XElement.Load("yourXML.xml");

var lstBooks=doc.Descendants("book").Select(x=>
new
{
    name=x.Element("title").Value,
    authors=x.Elements("author").Select(y=>y.Element("name").Value)
}
);

lstBooks now contains all the required data

You can now do this

foreach(var book in lstBooks)
{
book.name;//Name of the book
    foreach(var author in book)
    {
        author;//name of the author
    }
}


来源:https://stackoverflow.com/questions/13081415/xml-how-to-grab-child-nodes-in-single-node-and-not-whole-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!