Answer the question
In order to leave comments, you need to log in
How to check if an element exists in an xml file?
Hello!
I am using LinqToXML. It is necessary to check the presence of the necessary elements in the xml file, since when trying to read non-existent elements, an exception occurs (which I, of course, process). However, I would like to first check for the existence of the necessary elements in order to change the program logic without exception.
For example, I use the construction:
IEnumerable<XElement> XMLDataList = XMLFile.Root.Element("FirstNode").Element("SecondNode").Descendants("NodesList");
Answer the question
In order to leave comments, you need to log in
My omission, did not specify. You need to check the entire path /FirstNode/SecondNode/NodesList for existence.
Is there a way other than a lot of nested ifs with checks for each node using the Any() method?
That is, I want to implement the following program logic:
If /FirstNode/SecondNode/NodesList exists
then step1
Otherwise step2.
In general, I solved my own question (LINQ to XML, probably, cannot do it any other way):
bool IsNodeExist = XMLfile.Elements().Any(node => node.Name == "Address");
Ivan Filatov , thanks for the tip!
Learn coolhackers :)
XMLFile.Root.Element("FirstNode").Element("SecondNode").Element("NodesList").Any();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question