<root>
<data name="ID1"></data>
<data name="ID2"></data>
</root>
XDocument xmlDoc = XDocument.Load(xmlFile);
bool exists = (from elem in xmlDoc.Descendants("root")
where elem.Element("data").Attribute("name").Value == "ID1"
select elem).Any();
It doesn’t see that ID1 already exists. What am I doing wrong?
Based on what you’ve shown, first I have to point out that the XML snippet is not valid XML. The
datanodes are not closed.Assuming this is a valid XML document, it would ultimately depend on what the type is for your variable
XMLDoc.If it was an
XDocument, then that code snippet should work and the value ofexistswould betrue. The document contains a descendant calledrootand it could go about its business.If it was an
XElementon the other hand, then that code snippet should fail and the value ofexistswould befalse. TheXMLDocvariable would be referring to therootelement already and there clearly isn’t any descendants calledroot.You should rewrite your query however, maybe something more like this: