raklos
raklos

Reputation: 28545

get xml attribute using linq

suppose i have xml similar to the below

<?xml version=”1.0” encoding=”UTF-8”?> 
<validate status=”yes” last_updated=”2009-07-05T11:31:12”> 
 etc...etc
</validate> 

in c# how can i get the value of status in the validate element?

there will only be one validate element. how can i do this with linq?...or if theres a simpler way maybe

Upvotes: 1

Views: 2747

Answers (3)

m3kh
m3kh

Reputation: 7941

    XDocument xdoc = XDocument.Load("file name");
    // string status = xdoc.Root.Attribute("status").Value;

@Marc's suggestion

    string status = (string)xdoc.Root.Attribute("status");

Upvotes: 8

BFree
BFree

Reputation: 103742

 string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> 
<validate status=""yes"" last_updated=""2009-07-05T11:31:12""> 
 etc...etc
</validate>
";

            var doc = XDocument.Parse(xml);
            var item = doc.Elements("validate").First().Attributes("status").First().Value;

            Console.WriteLine(item);

Upvotes: 5

John Gietzen
John Gietzen

Reputation: 49534

XmlDocument doc = new XmlDocument();
doc.Load(...);
doc.DocumentElement.Attributes["status"].Value

is one way.

Upvotes: 1

Related Questions