2011-06-14 45 views
2

我有一個像下面的XML文檔:獲得一個搜索關鍵字的前一個節點在XML

<bookstore> 
    <book> 
    <title>The Autobiography of Benjamin Franklin</title> 
    <author> 
    <first-name>Benjamin</first-name> 
    <last-name>Franklin</last-name> 
    </author> 
    <price>8.99</price> 
    </book> 
    <book> 
    <title>Zen and the Art of Motorcycle Maintenance</title> 
    <author> 
    <first-name>Robert</first-name> 
    <last-name>Pirsig</last-name> 
    </author> 
    <price>5.99</price> 
    </book> 
    <book> 
    <title>Other Cities</title> 
    <author> 
    <first-name>Benjamin</first-name> 
    <last-name>Rosenbaum</last-name> 
    </author> 
    <price>9.99</price> 
    </book> 
</bookstore> 

當然,書店有超過一成書,所以二要搜索的作者,然後爲包含搜索的作者姓名的書籍節點返回XElement

+0

只是第一個''節點或所有匹配的''節點? – Kev 2011-06-14 16:08:16

回答

3
var document = XDocument.Parse(xml); 

var bookElements = document.Descendants("book") 
    .Where(arg => arg.Element("author").Element("first-name").Value == "Benjamin") 
    .ToList(); 

var bookElements = document.Descendants("first-name") 
    .Where(arg => arg.Value == "Benjamin") 
    .Select(arg => arg.Parent.Parent) 
    .ToList(); 

[編輯]正如你繼續編輯的問題,我將編輯答案:)。

找到符合條件的第一本書:

var foundBookElement = document.Descendants("book") 
    .Where(arg => arg.Element("author").Element("first-name").Value == "Benjamin") 
    .FirstOrDefault(); 

foundBookElement將是無效的,如果沒有的書籍符合標準。

+0

我需要一個xelement而不是列表 – hWorld 2011-06-14 16:00:20

+0

在這種情況下,使用.FirstOrDefault()而不是.ToList() – codymanix 2011-06-14 16:04:30

+0

@Dominique - 用'First()'替換'ToList()'。 – 2011-06-14 16:04:57

相關問題