Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read XML attributes in C#?

Tags:

c#

xml

I have several XML files that I wish to read attributes from. My main objective is to apply syntax highlighting to rich text box.

For example in one of my XML docs I have: <Keyword name="using">[..] All the files have the same element: Keyword.

So, how can I get the value for the attribute name and put them in a collection of strings for each XML file.

I am using Visual C# 2008.

like image 912
Mohit Deshpande Avatar asked Nov 01 '09 12:11

Mohit Deshpande


2 Answers

The other answers will do the job - but the syntax highlighting thingy and the several xml files you say you have makes me thinks you need something faster, why not use a lean and mean XmlReader?

private string[] getNames(string fileName)
{

  XmlReader xmlReader = XmlReader.Create(fileName);
  List<string> names = new List<string>(); 

  while (xmlReader.Read())
  {
   //keep reading until we see your element
   if (xmlReader.Name.Equals("Keyword") && (xmlReader.NodeType == XmlNodeType.Element))
   {
     // get attribute from the Xml element here
     string name = xmlReader.GetAttribute("name");
     // --> now **add to collection** - or whatever
     names.Add(name);
   }
  }

  return names.ToArray();
}

Another good option would be the XPathNavigator class - which is faster than XmlDoc and you can use XPath.

Also I would suggest to go with this approach only IFF after you try with the straightforward options you're not happy with performance.

like image 64
JohnIdol Avatar answered Oct 15 '22 10:10

JohnIdol


You could use XPath to get all the elements, then a LINQ query to get the values on all the name atttributes you find:

 XDocument doc = yourDocument;
 var nodes = from element in doc.XPathSelectElements("//Keyword")
             let att = element.Attribute("name")
             where att != null
             select att.Value;
 string[] names = nodes.ToArray();

The //Keyword XPath expression means, "all elements in the document, named "Keyword".

Edit: Just saw that you only want elements named Keyword. Updated the code sample.

like image 24
driis Avatar answered Oct 15 '22 11:10

driis