XDocument后代

Joh*_*ann 6 c# xml

<?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>
Run Code Online (Sandbox Code Playgroud)

我想得到GOBS-2的Cynthia1.注意GOBS-1还有另一个Cynthia1

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)
                                        {
                                        }
                                    }
                                }
                            }
                        }
Run Code Online (Sandbox Code Playgroud)

问题是,在从Gobs-2找到Cynthia1后,循环上升到Gobs-1.我认为对于sintal的第二个foreach存在问题,或许我应该使用不同的东西.我想在找到Gobs-2的sintal之后就停止了.似乎2个foreach没有关联.每个人都跑

Hen*_*man 11

我想得到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();
Run Code Online (Sandbox Code Playgroud)

  • 很棒的答案+1你可以把地方移到单身来缩短`.Single(s => s.Value =="Cynthia2"); (2认同)