开发者

XPath Query C# to pull out nodes dynamically

开发者 https://www.devze.com 2023-04-09 03:32 出处:网络
I amhaving to write a XPath Query to pull out the answer for a question based on the question id. The question id is passed dynamically to the query. I cannot use LINQ as the solution is in NET 2.0.Pl

I am having to write a XPath Query to pull out the answer for a question based on the question id. The question id is passed dynamically to the query. I cannot use LINQ as the solution is in NET 2.0. Please find the XML file below

<?xml version="1.0" encoding="utf-8" ?>
<Questionaire>
  <question id="1">
    <answer>1</answer>
    <correctAnswer>Text&l开发者_如何学Pythont;/correctAnswer>
  </question>
  <question id="2">
    <answer>2</answer>
    <correctAnswer>Text</correctAnswer>
  </question>
</Questionaire>

I'am a novice to XPath and find it hard to get my head around it.

Many thanks in advance.


You could use the XmlDocument class and the SelectSingleNode method to perform XPath queries. You may checkout the following article for examples. In your case the XPath query will be something along the lines of Questionaire/question[id='1'] where the id could be variable of course in order to fetch the corresponding node. Once you find the <question> node corresponding to your search criteria you could navigate to its child nodes.


Your XPath expression can be dynamically generated like this:

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

then, depending on the object representing the XML document you need to call one of the following methods: Select(), SelectNodes(), SelectSingleNode(), Evaluate().

Read the MSDN documentation about the appropriate methods of XmlDocument, XPathDocument, XPathNavigator and XPathExpression.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号