2011-09-29 83 views
1

我不得不編寫一個XPath查詢來根據問題ID抽出一個問題的答案。問題id被動態傳遞給查詢。我無法使用LINQ,因爲解決方案在.NET 2.0中。請在下面找到XML文件XPath查詢C#動態拉出節點

<?xml version="1.0" encoding="utf-8" ?> 
<Questionaire> 
    <question id="1"> 
    <answer>1</answer> 
    <correctAnswer>Text</correctAnswer> 
    </question> 
    <question id="2"> 
    <answer>2</answer> 
    <correctAnswer>Text</correctAnswer> 
    </question> 
</Questionaire> 

我是XPath的新手,很難找到我的頭。

非常感謝提前。

回答

0

你的XPath表達式可以動態地這樣產生:

myExpression = string.Format("/*/*[id='{0}']/answer", theId); 

然後,根據不同的對象表示你需要調用下面的方法之一的XML文檔:Select()SelectNodes()SelectSingleNode()Evaluate()

閱讀MSDN文檔有關XmlDocumentXPathDocumentXPathNavigatorXPathExpression適當的方法。

+0

非常感謝所有的貢獻。我最終接近@Dimitre的答案,但在這裏找到了他的答案,並且工作正常。再次感謝你們的搖滾! – Chin

+0

@Chin:不客氣。 –

3

您可以使用XmlDocument類和SelectSingleNode方法執行XPath查詢。例如,您可以結帳following article。在你的情況下,XPath查詢將沿着Questionaire/question[id='1']的行,其中id可能是可變的,以便獲取相應的節點。一旦找到<question>節點對應於您的搜索標準,您可以導航到其子節點。

+0

@_Darine,OP想要選擇答案,而不是問題。這可以通過評估一個XPath表達式來完成。 :) –