0

I have an XML file with the following structure:

<tu>
    <tuv xml:lang="EN">
        <seg>XXX</seg>
    </tuv>
    <tuv xml:lang="FR">
        <seg>YYY</seg>
    </tuv>
</tu>
<tu>
    <tuv xml:lang="EN">
        <seg>XXX</seg>
    </tuv>
    <tuv xml:lang="FR">
        <seg>YYY</seg>
    </tuv>
</tu>
...

And I would like to delete the node <tu> when <seg>XXX</seg> is equal to <seg>YYY</seg> from a C# application. I have tried with linq and in some other ways, but I wasn't able to compare those internal valuea and then delete the parent node if necessary.

Thanks a lot in advance!

marynarz
  • 43
  • 4
  • I have tried linq code found in other similar questions here (like http://stackoverflow.com/questions/919645/how-to-delete-node-from-xml-file-using-c/919687#919687). The problem I have is that all samples show how to query, select and delete, but I can't find anything that also compares internal values... – marynarz Sep 30 '11 at 15:34

1 Answers1

1

First of all your XML is invalid so I added a <root> node - then this worked for me:

XDocument doc = XDocument.Load("test.xml");

var nodesWithMatchingElements = doc.Root.Elements("tu")
                                   .GroupBy(e => e)
                                   .Select(g => new 
                                    { 
                                       Element = g.Key, 
                                       Count = g.Descendants("seg").Select(x => x.Value).Distinct().Count() 
                                    })
                                   .Where(x => x.Count == 1);

foreach (var node in nodesWithMatchingElements)
    node.Element.Remove();
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335