Search code examples
c#xmlxmlreader

How to get attribute xml without loop c#


i have xml file like this

> <?xml version='1.0' ?> 
   <config> 
     <app> 
       <app version="1.1.0" />
>    </app>
   </config>

and i want to read attribute version from node app without any loop like this while(reader.read()) or foreach etc.

Thanks


Solution

  • You can do it this way.

    XmlDocument doc = new XmlDocument();
    string str = "<config><app><app version=" + "\"1.1.0\"" + "/></app></config>";
                doc.LoadXml(str);
                var nodes = doc.GetElementsByTagName("app");
                foreach (XmlNode node in nodes)
                {
                    if (node.Attributes["version"] != null)
                    {
                        string version = node.Attributes["version"].Value;
                    }
                }
    

    And you need to this for loop cause you got two nodes with same name App. If you have a single node with name App,

    XmlDocument doc = new XmlDocument();
                string str = "<config><app version=" + "\"1.1.0\"" + "/></config>";
                doc.LoadXml(str);
                var node = doc.SelectSingleNode("//app");
                    if (node.Attributes["version"] != null)
                    {
                        string version = node.Attributes["version"].Value;
                        Console.WriteLine(version);
                    }