views:

54

answers:

2

I am using the following XML structure

<SERVERS>
<SERVER NAME="A1" ID="1"></SERVER>
<SERVER NAME="A2"></SERVER>
<SERVER NAME="A3" ID="3" Parent="XYZ"></SERVER>
<SERVER NAME="A4" ID="4"></SERVER>
<SERVER NAME="A5" Parent="abc" value="10"></SERVER>
<SERVER NAME="A6"></SERVER>
</SERVERS>

I am accessing this xml file by using LINQ to XML in asp.net by using C#. I am able to access all the attributes of an XML node by explicitly specifying the name of the attribute. I want to write query on this xml file which reads all the attribute values of the xml node (In our example the node is SERVER) dynamically means I want to write the query which can read the read the value of the attribute Name & ID from first node, only name from second row, Name, ID & Parent from the third row , Name & ID from the fourth row, Name, Parent & Value from the fifth row & only Name from the sixth row without modifying the existing code every time. Once I add one of the attribute ( for example if I add the attribute ID in the sixth row ) in the above xml file then I dont need to modify my LINQ to XML query. My query should dynamically fetch the total number of attributes & display their values. Is their any way to do this ? Can you provide me the any code or link through which I can resolve the above issue ?

A: 

If you just use XElement.Attributes() you'll get all the attributes for a particular element - you can loop through them appropriately.

Sample code:

using System;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string xml = "<element attr1='Hello' attr2='there' />";
        XElement element = XElement.Parse(xml);
        foreach (XAttribute attr in element.Attributes())
        {
            Console.WriteLine("{0}={1}", attr.Name, attr.Value);
        }
    }
}

Output:

attr1=Hello
attr2=there

So you just need to loop through all the elements you're interested in, and loop through the attributes within each element, displaying whatever you need to.

Jon Skeet
A: 

The below code will print out all attributes of an element.

XDocument doc = XDocument.Load("file.xml");
foreach(var element in doc.Element("SERVER").Elements()) {
  System.Diagnostics.Debug.WriteLine("Node " + element.Name.LocalName + ":");
  foreach(var attribute in element.Attributes()) {
     System.Diagnostics.Debug.WriteLine("  " + attribute.Name.LocalName + ": " + attribute.Value);
  }
}

For this XML:

<SERVER>
 <ServerInstance ID="101" Name="Server1">
 <ServerInstance ID="102" Name="Server2">
<SERVER>

It will print out something like this:

Node ServerInstance:
  ID: 101
  Name: Server1
Node ServerInstance:
  ID: 102
  Name: Server2
Igor Zevaka