0

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?

5
  • 2
    There are other ways, but your XPath expression is valid, and node being null indicates there is no <SurveySetting> element in your document. Are you absolutely sure that element is always present? Commented Sep 2, 2013 at 10:23
  • As @FrédéricHamidi said,Before setting the RadioButtonSurveySetting, check the Value with null.If it is not null then set it. Commented Sep 2, 2013 at 10:28
  • First search this way to avoid NULL.. Use //SurveySetting[not(@IsServeyOn)] Commented Sep 2, 2013 at 10:28
  • @Babai, do you mean //SurveySetting[@IsServeyOn], in case the element exists but its attribute doesn't? Commented Sep 2, 2013 at 10:32
  • @FrédéricHamidi Yes..I mean that.. Commented Sep 2, 2013 at 10:35

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.