2011-11-10 79 views
0

我有一個XmlDocument格式如下。如果我執行以下搜索:C#XmlNode的祖先類型

XmlNode title = xmlDoc.SelectNodes("//Book/Title[contains(., \"Title3\")]"); 

我將找回一個標題爲XmlNode。我如何知道該書是否屬於出版物?我並不總是想假設title.ParentNode.ParentNode.ParentNode存在。應該是說,一個直觀的方式:

if(title.hasAncestor("Publication") != null) 
{ 
    // do whatever 
} 

任何幫助,將不勝感激

<Publications> 
    <Novel> 
     <Book> 
      <Title>Title1</Title> 
      <Author>Author1</Author> 
      <Year>2000</Year> 
     </Book> 
     <Book> 
      <Title>Title2</Title> 
      <Author>Author2</Author> 
      <Year>2000</Year> 
     </Book> 
    </Novel> 
    <History> 
     <Book> 
      <Title>Title3</Title> 
      <Author>Author3</Author> 
      <Year>2000</Year> 
     </Book> 
     <Book> 
      <Title>Title4</Title> 
      <Author>Author4</Author> 
      <Year>2000</Year> 
     </Book> 
    </History> 
</Publications> 
<StudyGuides> 
    <Math> 
     <Book> 
      <Title>Title5</Title> 
      <Author>Author5</Author> 
      <Year>2000</Year> 
     </Book> 
     <Book> 
      <Title>Title6</Title> 
      <Author>Author6</Author> 
      <Year>2000</Year> 
     </Book> 
    </Math> 
    <Science> 
     <Book> 
      <Title>Title7</Title> 
      <Author>Author7</Author> 
      <Year>2000</Year> 
     </Book> 
     <Book> 
      <Title>Title8</Title> 
      <Author>Author8</Author> 
      <Year>2000</Year> 
     </Book> 
    </Science> 
</StudyGuides> 

回答

0

您可以在XPath中做到這一點通過ancestor軸:

//Book/Title[contains(., "Title3")][ancestor::Publications] 
+0

感謝您及時的回覆。我得到這將帶來出版物下的「Title3」的innerText的所有標題節點。但是如果我有一個XmlNode,那麼如果它在出版物或StudyGuides下面呢? 也許我看着它錯了?可能我需要查看該節點是否是XmlDocument中「Publications」下的子節點? – Koenyn

+0

@Koenyn如果你有'Title'節點作爲'XmlNode',那麼可以使用'XmlNode.ParentNode'遞歸或'titleNode.SelectSingleNode(「。[ancestor :: Publications]」)== null'。 – Richard

+0

:)謝謝。真的很感激它。我不得不將它改爲titleNode.SelectSingleNode(「ancestor :: Publications」)== null – Koenyn

0
/Publications/*/Book/Title[contains(., 'Title3')]