Amith Suresh
Amith Suresh

Reputation: 27

XPath C# Attribute value

The following is the XML file read into XmlDocument

<Test xmlns="http://api.test.com/v2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Result id="2015" description="Invalid Token" />
</Test >

What I need is the 'id' attribute value ("2015") stored in some TextBox

This is how XmlDocument is loaded

XmlDocument updateUser = new XmlDocument();
updateUser.Load(response.GetResponseStream());

Works well till here.

Then, create namespace and search for node

XmlNamespaceManager nsmgr = new XmlNamespaceManager(updateUser.NameTable);
nsmgr.AddNamespace("restup", "http://api.test.com/v2");

XmlNodeList locationElements1 = updateUser.SelectNodes("//restup:Test", nsmgr);
foreach (XmlNode Test in locationElements1)
{
//What DO I do here to get the value of 'id' attribute from the 'Result' node and save it in txtTest Textbox.

}

Upvotes: 1

Views: 733

Answers (3)

Samer_Azar
Samer_Azar

Reputation: 433

hello this is another method that can be useful

XmlTextReader reader = new XmlTextReader(fileLocation); //fileLocation is the Path of the XML file
while (reader.Read())
{

  if (reader.NodeType == XmlNodeType.Element) //if the node is an element (not a comment, CDATA, or text)
     if (reader.Name == "Result")
       textBox1.Text = reader.GetAttribute("id");

}
reader.Close();

Upvotes: 0

Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

string idString = Test.FirstChild.Attributes["id"].ToString();

Upvotes: 0

Juan Ayala
Juan Ayala

Reputation: 3528

var id = Test.FirstChild.Attributes["id"].Value;

Upvotes: 3

Related Questions