xpath显示来自不同级别的节点的数据

时间:2012-10-18 09:29:38

标签: c# xpath

<?xml version="1.0"?>

-<bookstore>            
        <book > 
            <title>aaaa</title> 
            -<author > 
                <first-name>firts</first-name> 
                <last-name>last</last-name> 
            </author> 
            <price>8.23</price> 
            <otherbooks>
                    <book > 
                        <title>bbb</title>      
                        <price>18.23</price> 
                    </book>     
                    <book > 
                        <title>ccc</title>      
                        <price>11.22</price> 
                    </book>     
            </otherbooks>
        </book> 
</bookstore>

我想选择不同级别的所有书籍,然后显示每个书籍(作者,标题和价格)的信息。目前代码还会显示第一本书的其他书籍。什么是仅显示所需信息的最佳方式。 我需要使用XPath。

xPathDoc = new XPathDocument(filePath);
xPathNavigator = xPathDoc.CreateNavigator();
XPathNodeIterator xPathIterator = xPathNavigator.Select("/bookstore//book");
foreach (XPathNavigator navigator in xPathIterator)
{
     XPathNavigator clone = navigator.Clone();
     clone.MoveToFirstChild();

     Console.WriteLine(clone.Name + " : " + clone.Value);
     while (clone.MoveToNext())
     {
         Console.Write(clone.Name + " : " + clone.Value + " | ");
     }
} 

2 个答案:

答案 0 :(得分:1)

双斜杠(//)指定all descendents,而不仅仅是直接斜杠。 <怎么样

/bookstore/book 

?这将只为您提供顶级book

答案 1 :(得分:1)

如果您愿意尝试使用Linq To Xml:

var xDoc = XDocument.Parse(xml); //or XDocument.Load(filename)
var books = xDoc.Root.Elements("book")
            .Select(b => new
            {
                Author = b.Element("author").Element("first-name").Value + " " +
                            b.Element("author").Element("last-name").Value,
                Books = b.Descendants("book")
                            .Select(x => new 
                            {
                                Title = x.Element("title").Value,
                                Price = (decimal)x.Element("price"),
                            })
                            .Concat(new[] { new { Title = b.Element("title").Value, 
                                                Price = (decimal)b.Element("price") } 
                                        })
                            .ToList()

            })
            .ToList();