Question

I am using C#, framework 3.5. I am reading xml values using xmldocument. I can get the values of attributes but i cannot get the attribute names. Example: My xml looks like

<customer>
 <customerlist name = AAA Age = 23 />
 <customerlist name = BBB Age = 24 />
</customer>

I could read values using the following code:

foreach(xmlnode node in xmlnodelist)
{
  customerName = node.attributes.getnameditem("name").value;
  customerAge = node.attributes.getnameditem("Age").value;
}

How to get attribute name (name,Age) instead of their values. Thanks

Was it helpful?

Solution

An XmlNode has an Attributes collection. The items in this collection are XmlAttributes. XmlAttributes have Name and Value properties, among others.

The following is an example of looping through the attributes for a given node, and outputting the name and value of each attribute.

XmlNode node = GetNode();

foreach(XmlAttribute attribute in node.Attributes)
{
    Console.WriteLine(
        "Name: {0}, Value: {1}.",
        attribute.Name,
        attribute.Value);
}

Beware, from the docs for the XmlNode.Attributes:

If the node is of type XmlNodeType.Element, the attributes of the node are returned. Otherwise, this property returns null.

Update

If you know that there are exactly two attributes, and you want both of their names at the same time, you can do something like the following:

string attributeOne = node.Attributes[0].Name;
string attributeTwo = node.Attributes[1].Name;

See http://msdn.microsoft.com/en-us/library/0ftsfa87.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top