I have an XML file that have two nodes with same name, and need to validate if the first one exist. I'm trying to do with SelectSingleNode and I found some XPath examples.
XML File
<root>
<header/>
<mensagem>
<header/>
<operacoes>
<operacao>
<titulo>
</operacao>
<operacao>
<titulo>
</operacao>
</operacoes>
</mensagem>
<trailer/>
</root>
Code
XmlDocument arquivoXml = new XmlDocument();
arquivoXml.Load(arquivo.ToString());
if (arquivoXml.DocumentElement.SelectSingleNode("root/header") != null)
{
// Tryed the condition above with XPath "../header" too
// If first header does exists
}
else
{
// If first header does not exists
}
The condition always do the same result if I remove one or another node. How can I validate the existence of an specific one?
Thanks
Given your XML, I think you want to check
if (arquivoXml.SelectSingleNode("root/header") != null)
or
if (arquivoXml.DocumentElement.SelectSingleNode("header") != null)
You do not even need XPath but could use
if (arquivoXml.DocumentElement["header"] != null)