78366

How to get attribute names of element in xml by LINQ in C#

Question:

I have xml element: <.SECTIONS> <.SECTION ID ="1" NAME="System Health" CONTROL-TYPE="Button" LINK="http://www.google.co.in/"> <.DATAITEMS> <./DATAITEMS> <./SECTION> <./SECTIONS>

I want to get the all attribute names of SECTION Element. as ID,NAME,CONTROL-TYPE,LINK at server side using LINQ to XML in C# language. What query I have to write there?

Answer1:

As @Giu mentions, your XML is technically malformed with the . preceding each element name.

To get the <em>names</em> of the attributes available in SECTION:

string xmlData = "<SECTIONS> <SECTION ID =\"1\" NAME=\"System Health\" CONTROL-TYPE=\"Button\" LINK=\"http://www.google.co.in/\"> <DATAITEMS> </DATAITEMS> </SECTION> </SECTIONS>"; XDocument doc = XDocument.Parse( xmlData ); //The above line could also be XDocument.Load( fileName ) if you wanted a file IEnumerable<string> strings = doc.Descendants("SECTIONS") .Descendants("SECTION") .Attributes() .Select( a => a.Name.LocalName );

This will give you an enumerable containing ID, NAME, CONTROL-TYPE, and LINK.

However, if you want the values contained in them, I would use @Giu's answer.

Answer2:

Your XML looks a little bit malformed due to the . before each tag name; I therefore sanitized your XML code by removing the .s, and made a solution based on the following XML code:

<SECTIONS> <SECTION ID ="1" NAME="System Health" CONTROL-TYPE="Button" LINK="http://www.google.co.in/"> <DATAITEMS> </DATAITEMS> </SECTION> </SECTIONS>

Thanks to the sanitized XML code, you now can use the following code snippet to achieve what you want (don't forget the using directive using System.Xml.Linq;):

XDocument doc = XDocument.Parse("<SECTIONS><SECTION ID =\"1\" NAME=\"System Health\" CONTROL-TYPE=\"Button\" LINK=\"http://www.google.co.in/\"><DATAITEMS></DATAITEMS></SECTION></SECTIONS>"); var query = from item in doc.Descendants("SECTIONS").Descendants("SECTION") select new { Name = (string)item.Attribute("NAME"), Id = (string)item.Attribute("ID"), ControlType = (string)item.Attribute("CONTROL-TYPE"), Link = (string)item.Attribute("LINK") };

(<em>Sidenote</em>: You can load your XML code directly from a file (e.g. file.xml), too, by defining the doc variable as follows:

XDocument doc = XDocument.Load(@"C:\Path\To\file.xml");

)

The following code will print the value of each attribute:

foreach (var elem in query) System.Console.WriteLine(string.Format("{0}, {1}, {2}, {3}", elem.Id, elem.Name, elem.ControlType, elem.Link));

Console output:

1, System Health, Button, http://www.google.co.in/

Recommend

  • database disk image is malformed or file is encrypted or is not a database
  • trim phone number with regex
  • git svn clone: branches moved from repo/ to repo/branches/ and “Malformed XML: no element found”
  • How do encryption algorithms know if they have the right key
  • Converting letters using a dictionary
  • Why does this regular expression evaluate to false in javascript?
  • How do I remove gloss from an iPhone app icon?
  • Can some data be separated in a Tcp connection?
  • Obtain nodes that don't have specific ancestor xml xpath
  • How can I validate a date including “00:07 PM” in JavaScript?
  • Why is this jQuery reference '$(“”)' instead of '$(“”)'?
  • Using JNA to Get NSWindow from JComponent on mac
  • Entity Framework connect to Oracle: ODP for .NET “does not support time”
  • Different builds of turn-based Game Center game can’t see each other’s matches
  • How read between delimiters in php DOM of a XML file?
  • Index.php as custom error page
  • Many to Many in Linq using Dapper
  • Multiple Left Join LINQ-to-entities
  • Exception creating JSON with LINQ
  • Do query loads all the data in memory
  • Merging rows to columns
  • NUnit 3.0 TestCase const custom object arguments
  • Linq Merge lists
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • Zurb Foundation _global.scss meta styles for js?
  • Android activity accessing service's static reference before the service is ready
  • ActiveRecord query for a count of new users by day
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • Play WS (2.2.1): post/put large request
  • PostgreSQL Query without WHERE only ORDER BY and LIMIT doesn't use index
  • Switching to Release Build causes runtime error in Web Reference
  • Email format validation in mvc3 view
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • How to add date and time under each post in guestbook in google app engine
  • Deserializing XML into class C#
  • Display Images one by one with next and previous functionality
  • Is there a mandatory requirement to switch app.yaml?
  • SQL merge duplicate rows and join values that are different
  • coudnt use logback because of log4j
  • How to Embed XSL into XML