2015-04-02 61 views
0

我在XML文件中有一些項目。例如。多個項目,如同一個文件中的下面的項目。我想搜索FluidTypes與特定字符串匹配的所有項目條目。在同一個名稱的多個標籤上的C#XML Linq

<?xml version="1.0" encoding="utf-8"?> 
<data> 
    <Project ID="P-2014-000037"> 
    <Name>FDP001_Bakken</Name> 
    <Manager>shell</Manager> 
    <Area>NAM</Area> 
    <Field>Bakken</Field> 
    <Type>Time and Material External</Type> 
    <Country>USA</Country> 
    <Value>3.5</Value> 
    <Geomarket>NAM</Geomarket> 
    <FormationTypes>Carbonate</FormationTypes> 
    <FormationTypes>Coal</FormationTypes> 
    <FormationTypes>Fractures</FormationTypes> 
    <FormationTypes>Sandstone</FormationTypes> 
    <FluidTypes>Gas Cond</FluidTypes> 
    <FluidTypes>Heavy Oil</FluidTypes> 
    <DriveMechanisms>Compaction</DriveMechanisms> 
    <DriveMechanisms>Aquifer</DriveMechanisms> 
    <EORProcesses>CO2</EORProcesses> 
    <EORProcesses>CSS</EORProcesses> 
    </Project> 
</data> 

我使用的follwing代碼來搜索Geomarket的相符:

IEnumerable<XElement> values1 = from el1 in root.Elements("Project"). 
     Where(r => regEx1.IsMatch(r.Element("Geomarket").Value)) 
            select el1; 

當我使用相同於流體類型(其具有多個元素):

 IEnumerable<XElement> values1 = from el1 in root.Elements("Project"). 
      Where(r => regEx1.IsMatch(r.Element("FluidTypes").Value)) 
             select el1; 

它僅檢查與名爲Fluid Types的第一個元素匹配,而不是所有流體類型元素。因此只有Gas Cond符合這個項目,但重油不符合。

如何在所有Fluid類型的搜索中進行查詢?

+0

爲什麼你不適合這樣的:IEnumerable的值1 = root.Elements( 「項目」)的元素( 「FluidTypes」); – 2015-04-02 19:43:56

+0

'我想搜索FluidTypes與特定字符串匹配的所有項目條目?例如? – EZI 2015-04-02 19:47:15

+0

例如:搜索流體類型=「重油」的所有項目 'Regex regEx1 = new Regex(「Heavy Oil」,RegexOptions.IgnoreCase);' – 2015-04-02 19:49:27

回答

3

使用Where子句與嵌套搜索:

 var projects = root 
      .Elements("Project") 
      .Where(el => el.Elements("FluidTypes").Where(el2 => regEx1.IsMatch(el2.Value)).Any()); 

這將返回名爲"Project"名爲"FluidTypes"Value正則表達式匹配至少一個嵌套元素的所有元素。

或者,使用嵌套Any()

 var projects = root 
      .Elements("Project") 
      .Where(el => el.Elements("FluidTypes").Any(el2 => regEx1.IsMatch(el2.Value))); 
+0

幾乎與我的問題一致,我會與這個答案一起去哈哈。 – Aizen 2015-04-02 21:36:57

+0

工作就像一個魅力。非常感謝 !!! – 2015-04-02 22:29:31

-2

嘗試

IEnumerable<XElement> values1 = from el1 in root.Elements("Project").Elements("FluidTypes") 
    .Where(r => regEx1.IsMatch(r.Value)) 
    Select el1; 
+0

謝謝。這對我的情況沒有幫助,因爲如果我做root.Elements(「Project」)。Elements(「FluidTypes」);那麼只有流體類型列註冊在我的IEnumerable 值1中。我需要整個元組,即我IEnumerable 值1中的所有列。 'IEnumerable的值1 =從root.Elements EL1( 「項目」) 。凡(R => regEx1.IsMatch(r.Value)) 選擇EL1;' 我想這和它似乎工作在這種情況下。然而,它會在所有元素中尋找匹配,而不僅僅是流體類型。 – 2015-04-02 22:10:06

相關問題