M
M
M3fist02015-11-30 15:23:36
.NET
M3fist0, 2015-11-30 15:23:36

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");

In this case, I get an exception if the xml file does not contain /FirstNode/SecondNode/NodesList elements.
On the topic in the search engines did not find anything worthwhile. It is advised to use XPath or XmlReader.
Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
M3fist0, 2015-11-30
@M3fist0

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 :)

I
Ivan Filatov, 2015-11-30
@NYMEZIDE

XMLFile.Root.Element("FirstNode").Element("SecondNode").Element("NodesList").Any();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question