Check if XML Element exists

后端 未结 13 1550
傲寒
傲寒 2020-12-03 06:20

How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing

13条回答
  •  有刺的猬
    2020-12-03 07:14

    You can iterate through each and every node and see if a node exists.

    doc.Load(xmlPath);
            XmlNodeList node = doc.SelectNodes("//Nodes/Node");
            foreach (XmlNode chNode in node)
            {
                try{
                if (chNode["innerNode"]==null)
                    return true; //node exists
                //if ... check for any other nodes you need to
                }catch(Exception e){return false; //some node doesn't exists.}
            }
    

    You iterate through every Node elements under Nodes (say this is root) and check to see if node named 'innerNode' (add others if you need) exists. try..catch is because I suspect this will throw popular 'object reference not set' error if the node does not exist.

提交回复
热议问题