2012-05-14 55 views
1

我有以下XML:如何獲取c#中的父節點文本值?

<?xml version="1.0"?> 
<catalog> 
    <book id="bk101"> 
     <author>Gambardella, Matthew</author> 
     <title>XML Developer's Guide</title> 
     <genre>Computer</genre> 
     <price>44.95</price> 
     <publish_date>2000-10-01</publish_date> 
     <description>An in-depth look at creating applications 
     with XML.</description> 
    </book> 
    <book id="bk102"> 
     <author>Ralls, Kim</author> 
     <title>Midnight Rain</title> 
     <genre>Fantasy</genre> 
     <price>5.95</price> 
     <publish_date>2000-12-16</publish_date> 
     <description>A former architect battles corporate zombies, 
     an evil sorceress, and her own childhood to become queen 
     of the world.</description> 
    </book> 
</catalog> 

我發現一個名爲 「三更雨」 的稱號。現在我想知道誰是他的父母,以便我可以使用<author>文本節點。我想是這樣的:

var xpath = "../*[local-name() != 'title']"; 
     xml.Load(xmlalltext); 
     var xl1 = xml.SelectNodes(xpath); 
     MessageBox.Show(xl1.Item(0).InnerText.ToString()); 

回答

3

如果你已經找到標題節點,你要尋找的父節點,你可以選擇當前節點的父節點。

var parentNode = titleNode.SelectSingleNode(".."); 

如果您正在尋找筆者節點:或者

var authorNode = titleNode.SelectSingleNode("../author"); 

,你可以找一前述或以下的兄弟姐妹:

var authorNode = titleNode.SelectSingleNode("following-sibling::author") ?? titleNode.SelectSingleNode("preceding-sibling::author"); 

編輯:要回答你的評論,如果您只有標題的字符串,那麼您可以使用以下方式獲取作者:

string xml = @"xml..."; 
var doc = XDocument.Parse(xml); 
string author = doc 
    .Descendants("book") 
    .Where(x => x.Element("title").Value == "Midnight Rain") 
    .Select(x => x.Element("author").Value) 
    .FirstOrDefault(); 
+0

我只是字符串「午夜雨」,我想搜索他的作者。我的確瞭解你的代碼的邏輯。謝謝! –

1

使用XLINQ

sample.xml中(以下剪斷)包含

 XElement root = XElement.Parse(File.ReadAllText("sample.xml")); 

     var matchingBooks = root.Descendants().Where(i=>String.Equals(i.Value,"Midnight Rain")).Select(i=>i.Parent) ; 
     var authors = matchingBooks.Elements("author"); 

產出LinqPad

matchingBooks.Dump(); 

authors.Dump(); 

<book id="bk102"> 
     <author>Ralls, Kim</author> 
     <title>Midnight Rain</title> 
     <genre>Fantasy</genre> 
     <price>5.95</price> 
     <publish_date>2000-12-16</publish_date> 
     <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description> 
     </book> 

<author>Ralls, Kim</author> 
0

你可以使用這個XPath expession對XML數據得到作者節點

"/catalog/book[title='Midnight Rain']/author" 

或這讓父節點

"/catalog/book[title='Midnight Rain']" 

如。

var result = xml.SelectNodes(string.Format("/catalog/book[title='{0}']/author", "Midnight Rain"))