Search code examples
c#xmlxmldocument

C# get values from xml attributes


How to get attribute "action" and "filename" values in a right way using C#?

XML:

<?xml version="1.0" encoding="utf-8" ?>
 <Config version="1.0.1.1" >
   <Items>
    <Item action="Create" filename="newtest.xml"/>
    <Item action="Update" filename="oldtest.xml"/>   
  </Items>
 </Config>

C#: i cannot get attribute values as well as how to get values in foreach loops? How to solve this?

        var doc = new XmlDocument();
        doc.Load(@newFile);
        var element = ((XmlElement)doc.GetElementsByTagName("Config/Items/Item")[0]); //null
        var xmlActions = element.GetAttribute("action"); //cannot get values
        var xmlFileNames= element.GetAttribute("filename"); //cannot get values

         foreach (var action in xmlActions)
         {
           //not working
         }

         foreach (var file in xmlFileNames)
         {
           //not working
         }

Your code example means alot to me. Thanks!


Solution

  • You can use LINQ to XML. Following query returns strongly typed collection of items with Action and FileName properties:

    var xdoc = XDocument.Load(@newFile);
    
    var items = from i in xdoc.Descendants("Item")
                select new {
                   Action = (string)i.Attribute("action"),
                   FileName = (string)i.Attribute("fileName")
                };
    
    foreach (var item in items)
    {
       // use item.Action or item.FileName
    }