2017-03-15 51 views
0

中提取數據,我有一個包含這樣的元素的列表:Linq的語句從的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>} 

我想幫助辨別來自上述名單隻提取「https://my.home.site.com」的價值觀所需要的LINQ的聲明<>。這裏的問題是,我們不僅可以使用<d:Value>,因爲只有此列表中具有<d:Key> Path值的XElement(如上例所示)實際上包含<d:Value>項中的URL。

有誰知道會執行上述數據提取的魔術Linq語句嗎?

+0

這些XElements從哪裏來?它只是一個列表? –

+0

首先,您可以將列表轉換爲POCO嗎?如果是這樣,那麼你可以做'myList.Where(x => x.key!= null)' 如果你不能最好的選擇是使用正則表達式來匹配key值的存在並且提取在價值標籤中。 –

+0

你最好的選擇絕對不會是使用正則表達式 – Jonesopolis

回答

2

假設你的數據從類似這樣的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並查看this瞭解更多XElement信息。

+0

非常棒!謝謝,那有效。 –

1

如果你確實有一個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,你只是修改查詢的開始略有下降。

0

我認爲這個問題,如果與naespace聲明。試試這個:

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); 
+0

你是正確的名稱空間是問題的一部分...這是我的代碼工作,基於amura.cxg的答案: var url =(from e in items.Elements(d +「element」) where e。 Element(d +「Key」)。Value ==「Path」 select e.Element(d +「Value」)。Value); –