Suppose I have a XmlNode and I want to get the value of an attribute named "Name". How can I do that?
XmlTextReader reader = new XmlTextReader(path);
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
**//Read the attribute Name**
if (chldNode.Name == Employee)
{
if (chldNode.HasChildNodes)
{
foreach (XmlNode item in node.ChildNodes)
{
}
}
}
}
XML Document:
<Root>
<Employee Name ="TestName">
<Childs/>
</Root>
Try this:
string employeeName = chldNode.Attributes["Name"].Value;
Edit: As pointed out in the comments, this will throw an exception if the attribute doesn't exist. The safe way is:
var attribute = node.Attributes["Name"];
if (attribute != null){
string employeeName = attribute.Value;
// Process the value here
}