如何使用XDocument和Linq获取元素的值到XML

时间:2014-04-17 13:17:58

标签: c# xml linq

我想用命名空间收集RequestID元素,但我不知道如何。

this.XmlString =  "<?xml version=\"1.0\" 
encoding=\"utf-8\"?><MethodNameRq xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" 
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><RequestID 
xmlns=\"http://Mynamespace\">573-348976-428697-346</RequestID ></MethodNameRq>";

var doc = XDocument.Parse(this.XmlString);

this.RequestId = (string)doc.Descendants().Where(n => n.Name 
                 == "RequestID ").FirstOrDefault();

这会为RequestID收集一个空字符串。如果字符串没有包含名称空间,它确实有效。有谁知道我如何收集RequestID元素?

1 个答案:

答案 0 :(得分:3)

您需要指定元素的命名空间

XNamespace ns = "http://Mynamespace";

this.RequestId = (string)doc.Descendants(ns + "RequestID").FirstOrDefault();