使用Linq To XML,我如何从下面的space_id中获取XML值(720)?
我正在阅读this,但我认为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>编辑
这就是我所在的地方:
private int GetIDFromXML(string xml)
{
XDocument xDoc = XDocument.Parse(xml);
// hmmm....
}发布于 2009-05-11 14:32:54
你也可以使用(对上面的代码稍作改动,我认为它更具可读性)
XNamespace ns = "http://www.collegenet.com/r25";
string id = doc.Descendants(ns.GetName("space_id").Single().Value;发布于 2009-05-05 16:29:36
如果您只想要唯一的space_id元素,而不需要查询等:
XNamespace ns = "http://www.collegenet.com/r25";
string id = doc.Descendants(ns + "space_id")
.Single()
.Value;(其中doc是XDocument -或XElement)。
发布于 2011-06-30 05:17:29
关于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();https://stackoverflow.com/questions/825714
复制相似问题