Search code examples
c#asp.netxmllinq-to-xmldynamic-data

How to dynamically retrive the all the possible attributes (variable attributes) values of one of the xml node?


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 ?


Solution

  • 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