简体   繁体   English

如何使用Linq To XML获取元素值

[英]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? 使用Linq To XML,如何从下面的xml中获取space_id值(720)?

I am reading this but I think the namespace in the xml is my stumbling block. 我正在读这个,但我认为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>

EDIT 编辑

Here's where I am: 我就在这里:

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

        // hmmm....
    }

If you just want the sole space_id element, with no querying etc: 如果你只想要唯一的space_id元素,没有查询等:

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

(Where doc is an XDocument - or an XElement ). (其中docXDocument - 或XElement )。

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;

A bit more verbose on Jon Skeets answer... Jon Skeets的答案更加冗长......

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM