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

本文关键字:元素 获取 Linq-to-XML 何使用 XDocument | 更新日期: 2023-09-27 17:58:43

我想收集带有名称空间的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元素吗?

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

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

XNamespace ns = "http://Mynamespace";
this.RequestId = (string)doc.Descendants(ns + "RequestID").FirstOrDefault();