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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.