CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2012
    Posts
    2

    Find Specific XML Node value

    I am currently trying to read in and parse an XML string that looks similar to:

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <test version="1.1">
      <query id="1234534567">
        <queryName>getHistory</queryName>
        <inputParameters>
          <parameter>
            <parameterName>requestorId</parameterName>
            <parameterValue>1111</parameterValue>
          </parameter>
          <parameter>
            <parameterName>employeeNumber</parameterName>
            <parameterValue>1111</parameterValue>
          </parameter>
          <parameter>
            <parameterName>IDNumber</parameterName>
            <parameterValue>123456</parameterValue>
          </parameter>
        </inputParameters>
      </query>
    </test>
    Seeing that I do not have unique node names, is it possible to grab a specific node value and return its counterpart. What I mean is, is there a way to look for the parameterName with a value of IDNumber and return its corresponding parameterValue? I have been unsuccessful thus far... Any help would be greatly appreciated.

  2. #2
    Join Date
    Jan 2007
    Posts
    491

    Re: Find Specific XML Node value

    Yes - using XPATH you can search for specific nodes. I believe something like that would work:
    Code:
    XmlDocument doc;
    //load your document to doc here...
    XmlNode node = doc.SelectSingleNode("test/query/inputParameters/" +
       "parameter[parameterValue/text() = IDNumber]/parameterValue");
    Console.WriteLine(node.InnerText);
    Your probably wonder what the XPATH query I wrote does.
    Well, here's a translation of this XPath query to plain English:
    -Look for an XML element named "test".
    -Then look for a child of "test" named "query".
    -Then look for a child of "query" named "inputParameters".
    -Then look for a "parameter" child that has a "parameterValue" child, whose text is "IDNumber".
    -Return the child named "parameterValue" of this parameter.

    Note that if there can be more than one parameters with paramaterName = "IDNumber", you should use the Select method instead of SelectSingleNode.
    SelectSingleNode will return the first node that matches your XPATH query, whereas Select will return a collection of all the nodes that match your XPATH query.

    In general, if you work with XML files, you should get familiar with XPATH - it's very useful.

    Tal.
    Last edited by Talikag; May 7th, 2012 at 07:25 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured