1
<?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 + " | ");
     }
} 
4

2 回答 2

1

双斜杠 ( //) 指定所有后代,而不仅仅是直接的后代。怎么样

/bookstore/book 

? 那只会让你达到最高水平book

于 2012-10-18T09:31:59.770 回答
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();
于 2012-10-18T09:54:37.390 回答