C# Get XML element value using XmlDocument

19,349

You should be able to just do this:

 myDoc.SelectNodes("/Model/BookStore/Book/Sub[@ID='Science']/Rank[@ID='Physics']");

And then confirm that you got exactly one result.

Share:
19,349
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    Trying to retrieve the value of Rank in the XML file example below... the path i'm passing works fine wit the SelectNodes method, except when i add the attribute to the path then the code will skip the foreach loop

    appreciate any help on how to solve this. in addition i'm looking for one value of the Rank element and its a based on specific attributes of Sub ID and Rank ID so there is no need for the loop but that's the only way i know

    XML File:

    <Model>
    
    <BookStore>
        <Book>
          <Sub ID="Science">
            <Rank ID="Chemistry">Value1</Rank>
            <Rank ID="Physics">Value2</Rank>
          </Sub>
        </Book>
    </BookStore>
    
    </Model>
    

    C# Code:

    var myDoc = new XmlDocument();
    myDoc.Load(MapPath("myXML.xml"));
    
    XmlNodeList rankList = myDoc.SelectNodes("/Model/BookStore/Book/Sub[@ID='Science']/Rank");  // Science can be any other variable
    foreach (XmlNode myRankNode in rankList)
    {
        if (myRankNode.Attributes["ID"].Value.ToString() == "Physics") // Physics can be any other variable
        {
            myValue = myRankNode.InnerText;
        }
    
    }