2014-03-18 34 views
3
<?xml version="1.0" encoding="ISO-8859-1"?> 
<kdd> 
<Table> 
    <robel ID="1"> 
     <groof NAME="GOBS-1"> 
      <sintal ID="A">Cynthia1</sintal> 
      <sintal ID="B">Sylvia2</sintal> 
      <sintal ID="C">Sylvia3</sintal> 
      <sintal ID="D">Sylvia4</sintal> 
     </groof> 
     <groof NAME="GOBS-2"> 
      <sintal ID="A">Cynthia1</sintal> 
      <sintal ID="B">Cynthia2</sintal> 
      <sintal ID="C">Cynthia3</sintal> 
      <sintal ID="D">Cynthia4</sintal> 
     </groof> 
     <groof NAME="GOBS-3"> 
      <sintal ID="A">Daniella1</sintal> 
      <sintal ID="B">Daniella2</sintal> 
      <sintal ID="C">Daniella3</sintal> 
      <sintal ID="D">Daniella4</sintal> 
     </groof> 
    </robel> 
</Table> 
</kdd> 

我想获得GOBS-2的Cynthia1。注意有来自GOBS-1XDocument后裔

foreach (XElement element in doc.Descendants("groof")) 
       { 
        string mmname = element.Attribute("NAME").Value.ToString(); 

         if (mmname == "GOBS-2") 
         { 
          bool found = false; 
          foreach (XElement element1 in doc.Descendants("sintal")) 
          { 

           if (found == false) 
           { 
            string CurrentValue = (string)element1; 
            if ("Cynthia1" == CurrentValue) 
            { 
             try 
             { 
              //do something 
              found = true; 
             } 
             catch (Exception e) 
             { 
             } 
            } 
           } 
          } 
         } 

的问题是,从采空区-2发现Cynthia1陆续Cynthia1,循环上升到采空区-1。 我认为第二个foreach存在问题,可能是我应该使用不同的东西。 我希望在找到Gobs-2的sintal之后,它会停止寻找。看来这2个foreach没有关系。每个自己

回答

10

运行我想获得GOBS-2的Cynthia1

您可以使用LINQ到那里更准确地说

XElement cynthia = doc 
    .Descendants("groof") 
    .Where(g => g.Attribute("NAME").Value == "GOBS-2") 
    .Elements("sintal") 
    .Where(s => s.Value == "Cynthia1") // or Attribute("ID") == "A" 
    .Single(); 
+1

很好的答案+1你可以移动到单一的位置来缩短'.Single(s => s.Value ==“Cynthia2”);' – paqogomez

+0

是的,我知道。但我并不总是觉得这更清楚。在这种情况下,这是一个折腾,我会这样离开它。分别显示所有步骤。 –

2

你必须在内部的foreach错误循环,你应该迭代element.Descendants("sintal")不是doc.Descendants("sintal")

foreach (XElement element in doc.Descendants("groof")) 
{ 
    string mmname = element.Attribute("NAME").Value.ToString(); 

    if (mmname == "GOBS-2") 
    { 
     bool found = false; 
     foreach (XElement element1 in element.Descendants("sintal")) 
     { 

      if (found == false) 
      { 
       string CurrentValue = (string)element1; 
       if ("Cynthia1" == CurrentValue) 
       { 
        try 
        { 
         //do something 
         found = true; 
        } 
        catch (Exception e) 
        { 
        } 
       } 
      } 
     } 
    } 
} 

您从第一个groof标签获得sintal元素的原因是doc.Descendants("sintal")查找文档中的第一个sintal标签,而不是您先前选择的父节点。