Reputation: 21
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;
}
}
Upvotes: 2
Views: 20454
Reputation: 3056
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.
Upvotes: 1