简体   繁体   中英

Selecting Node from xml file using xpath

My XML file is as:

<?xml version="1.0" encoding="UTF-8"?>
   <Settings>
     <SurveySetting IsServeyOn="false" />
   </Settings>

I want to fetch the value of IsServeyOn.
I write the below code for that:

XmlDocument xmlDoc  = new XmlDocument();
xmlDoc.Load(filepath);
XmlElement root  = xmlDoc.DocumentElement;
XmlNode node  = root.SelectSingleNode("//SurveySetting");
RadiobuttonSurverysetting.SelectedValue  = node.Attributes["IsServeyOn"].Value;

But sometimes it gives me error.. Node not found or NUll.
Is any other way to select the node?

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filepath);
XmlElement root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("SurveySetting");
if (node != null && node.Attributes.Count > 0 && node.Attributes["IsServeyOn"] != null && !string.IsNullOrEmpty(node.Attributes["IsServeyOn"].Value))
  {
        RadiobuttonSurverysetting.SelectedValue = node.Attributes["IsServeyOn"].Value;
  }

I have tried your code by putting some validations and it works fine in my application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM