C# 中的 Linq 语句从 XElement 中提取数据

Linq statement in C# to extract data from XElement

我有一个包含如下元素的列表:

{<d:element m:type="SP.KeyValue" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
  <d:Key>Path</d:Key>
  <d:Value>https://my.home.site.com</d:Value>
  <d:ValueType>Edm.String</d:ValueType>
</d:element>}

我想帮助您辨别从上述 List<> 中仅提取“https://my.home.site.com”值所需的 Linq 语句。这里的问题是我们不能只使用 <d:Value> 因为只有在这个列表中具有 Path 的 <d:Key> 值的 XElements,就像上面的例子一样,实际上在 <d:Value> 键中包含 URL .

有谁知道执行上述数据提取的神奇 Linq 语句?

假设您的数据来自 XML 类似于此的文件:

<?xml version="1.0"?>
<root xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
    <d:element m:type="SP.KeyValue">
        <d:Key>Path</d:Key>
        <d:Value>https://my.home.site.com</d:Value>
        <d:ValueType>Edm.String</d:ValueType>
    </d:element>
    <d:element m:type="SP.KeyValue">
        <d:Key>NotPath</d:Key>
        <d:Value>https://my.home.site.com</d:Value>
        <d:ValueType>Edm.String</d:ValueType>
    </d:element>
</root>

以下代码:

XElement  root = XElement.Load("Some file");
List<string> urls;

//Query Syntax
urls = (from e in root.Elements(d + "element")
        where e.Element(d + "Key").Value == "Path"
        select e.Element(d + "Value").Value);
//Or

//Method Syntax
urls = (from e in root.Elements(d + "element")
        where e.Element(d + "Key").Value == "Path"
        select e.Element(d + "Value").Value).ToList();

Console.WriteLine(string.Join(",", urls));

将导致(注意它会忽略 "NotPath" 键):

https://my.home.site.com

您可以查看实时示例 here and check out this 了解更多 XElement 信息。

如果您实际上有一个 ListXElement:

var list = new List<XElement>(); //however you get your XElement collection

var values = list.Where(x => x.Elements().First(e => e.Name.LocalName == "Key").Value == "Path")
                 .Select(x => x.Elements().First(e => e.Name.LocalName == "Value").Value)

如果您有 XDocument,您只需稍微修改查询的开头即可。

我认为命名空间声明会带来问题。试试这个:

string xml = "<d:element m:type=\"SP.KeyValue\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\">"+
"<d:Key>Path</d:Key>"+
"<d:Value>https://my.home.site.com</d:Value>"+
"<d:ValueType>Edm.String</d:ValueType>"+
"</d:element>";

XDocument xmlObj = XDocument.Parse(xml);
XNamespace ns_d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
var result = xmlObj.Descendants(ns_d + "Value").Select(x => x.Value);