Re: ReadXML True vs true



"Steve" <steve_jacobs@xxxxxxxxxxxxx> wrote in
news:1114177753.376832.286050@xxxxxxxxxxxxxxxxxxxxxxxxxxxx:

> I've run across an issue that I'm trying to work around. I take
> that back, I have a work around but I'm looking to see if anyone
> has a fix for it.
>
> The issue is that when loading a Boolean into a dataset using
> ReadXml, .NET requires the "true" or "false" to be all lower
> case or 1 and 0. If you use "True" or have any character
> capitalized, you get a System.FormatException saying, "The
> string was not recognized as a valid Boolean value."
>
> The issue I have is that sometimes the XML is edited manually. I
> can't guarantee that the person editing it won't unintentionally
> put "True".
>
> I have a simple work around, I just catch the exception, find
> and replace in the file and call ReadXml again but I'm looking
> to see if a fix exist out there for it.

Steve,

The behavior you're seeing is due to how the
System.Xml.XmlConvert.ToBoolean method works. As you observed, it
converts "true" or 1 to true, and "false" or 0 to false.
Anything else will throw a System.FormatException.

The only immediate fix I can think of is the one you are
already doing. If the XML file is small enough, and/or
the exception occurs more often then not, then you may
consider changing the algorithm. You could load the XML
file into a string, do any necessary replacements, and then
call a different version of ReadXml:

string xmlContents = string.Empty;
using (StreamReader sr = new StreamReader(@"C:\Test.xml"))
xmlContents = sr.ReadToEnd();

xmlContents = Regex.Replace(xmlContents, ">\s*?true\s*?<", ">true<", RegexOptions.IgnoreCase);
xmlContents = Regex.Replace(xmlContents, ">\s*?false\s*?<", ">false<", RegexOptions.IgnoreCase);

ds.ReadXml(new XmlTextReader(new StringReader(xmlContents));

--
Hope this helps.

Chris.
-------------
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/
.


Loading