views:

468

answers:

3

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....
    }
+3  A: 

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).

Jon Skeet
Is there a way to get the namespace from the XDocument object created by XDocument.Parse(myXMLString)?
Ronnie Overby
You could get doc.Root.Name.Namespace
Jon Skeet
A: 

You should be able to get that through XElement.Value.

Andy
Example please?
Ronnie Overby
+1  A: 

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;
Johan Leino