1

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

Raghul Raman
  • 169
  • 1
  • 5
  • 18

1 Answers1

1

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

Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
  • Thanks for your reply. So i would like to read the attribute names for the element as a pair like if(1stAttribute.name == "Name" and 2ndAttribute.Name = "Age") then do something. So i need customize the code based on attribute names. So how to get the all the attribute names associated with that element. – Raghul Raman Oct 22 '12 at 19:50
  • Thanks seth. Yes for now it is going to be 2 attributes but i am not sure what has to be done if i want it more generic. – Raghul Raman Oct 22 '12 at 19:59