Ronnie Overby
Ronnie Overby

Reputation: 46470

How to get elements value with Linq To XML

Using Linq To XML, how can I get the space_id value (720) from the xml below?

I am reading this but I think the namespace in the xml is my stumbling block.

<r25:spaces xmlns:r25="http://www.collegenet.com/r25" pubdate="2009-05-05T12:18:18-04:00">
  <r25:space id="VE1QOjRhMDAyZThhXzFfMWRkNGY4MA==" crc="" status="new">
    <r25:space_id>720</r25:space_id>
    <r25:space_name>SPACE_720</r25:space_name>
    <r25:max_capacity>0</r25:max_capacity>
  </r25:space>
</r25:spaces>

EDIT

Here's where I am:

private int GetIDFromXML(string xml)
    {
        XDocument xDoc = XDocument.Parse(xml);

        // hmmm....
    }

Upvotes: 2

Views: 5071

Answers (3)

barrypicker
barrypicker

Reputation: 10088

A bit more verbose on Jon Skeets answer...

string xml = @"<r25:spaces xmlns:r25=""http://www.collegenet.com/r25"" pubdate=""2009-05-05T12:18:18-04:00"">"
    + @"<r25:space id=""VE1QOjRhMDAyZThhXzFfMWRkNGY4MA=="" crc="""" status=""new"">"
    + @"<r25:space_id>720</r25:space_id>"
    + @"<r25:space_name>SPACE_720</r25:space_name>"
    + @"<r25:max_capacity>0</r25:max_capacity>"
    + @"</r25:space>"
    + @"</r25:spaces>";

XDocument xdoc = XDocument.Parse(xml);
XNamespace ns = "http://www.collegenet.com/r25";

var value = (from z in xdoc.Elements(ns.GetName("spaces"))
             .Elements(ns.GetName("space"))
             .Elements(ns.GetName("space_id")) 
         select z.Value).FirstOrDefault();

Upvotes: 0

Johan Leino
Johan Leino

Reputation: 3533

You can also go with (slight variation of the code above which I think is a bit more readable)

XNamespace ns = "http://www.collegenet.com/r25";
string id = doc.Descendants(ns.GetName("space_id").Single().Value;

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500515

If you just want the sole space_id element, with no querying etc:

XNamespace ns = "http://www.collegenet.com/r25";
string id = doc.Descendants(ns + "space_id")
               .Single()
               .Value;

(Where doc is an XDocument - or an XElement).

Upvotes: 6

Related Questions