How to get elements value with Linq To XML

↘锁芯ラ 提交于 2020-01-04 09:12:59

问题


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

回答1:


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;



回答2:


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




回答3:


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();


来源:https://stackoverflow.com/questions/825714/how-to-get-elements-value-with-linq-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!