-3

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

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Alexandr Sargsyan
  • 656
  • 1
  • 6
  • 21

3 Answers3

1
XmlDocument document = new XmlDocument();
document.Load("D:/source.xml");

XmlNode appVersion1 = document.SelectSingleNode("//app[@version]/@version");
XmlNode appVersion2 = document["config"]["app"]["app"].Attributes["version"];

Console.WriteLine("{0}, {1}", 
    appVersion1.Value, 
    appVersion2.Value);
Denis
  • 5,894
  • 3
  • 17
  • 23
0

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);
                }
Lekha
  • 31
  • 3
0

You can use linq to do

    string stringXml= "yourXml Here";
    XElement xdoc = XElement.Parse(stringXml);

    var result= xdoc.Descendants("app").FirstOrDefault(x=> x.Attribute("version") != null).attribute("version").Value;

or:

    var result = xdoc.Descendants("app").Where(x => x.Attribute("version") != null)
                                        .Select(x => new { Version =  x.Value });
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160