Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to parse an XML boolean attribute (in .NET)?

An XML attribute declared as xs:boolean can acceptable be "true", "false", "0" or "1". However, in .NET, Boolean.Parse() will only accept "true" or "false". If it sees a "0" or "1", it throws a "Bad Format" exception.

So, given that, what's the best way to parse such a value into a Boolean?

(Unfortunately, I'm limited to .NET 2.0 solutions, but if v3.5 offers something, I'd love to hear about it.)

like image 269
James Curran Avatar asked Nov 05 '08 15:11

James Curran


People also ask

How do you represent a boolean in XML?

Syntax of XML boolean xml version="1.0" encoding="utf-8"?> Following is a boolean declaration in schemas. The value of a boolean is an Integer value whose values are '0' and '1', representing logical yes or no.

What is boolean in XML?

A boolean is an XML schema primitive data type, as specified in [XMLSCHEMA2/2] section 3.2. 2. It is declared as an element with a type attribute of "boolean". The value of a boolean element is an integer whose only valid values are 1 (TRUE) or 0 (FALSE).

What is XML parsing in Android?

Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files.

Can XML attributes be empty?

Outgoing XML attributes mapped to fieldsIf a field is null, AR System generates an attribute with empty content. If a character field contains an empty string, AR System generates an attribute with empty content.


2 Answers

I think that XmlConvert has all the methods for converting between common language runtime types and XML types. Especially XmlConvert.ToBoolean handles exactly the boolean values (valid strings are "1" or "true" for true and "0" or "false" for false).

like image 134
Panos Avatar answered Oct 07 '22 03:10

Panos


Using CBool instead of Boolean.Parse should do the trick: although you'll have to embed it in a try/catch block (which wouldn't be required when using Boolean.TryParse), it will successfully convert most 'sensible' boolean values, including true/false and 0/1.

Edit: as pointed out in a comment, this answer is kinda useless for C# programmers, as CBool is a VB-ism. It maps to Microsoft.VisualBasic.CompilerServices.Conversions::ToBoolean, which is not suitable for general consumption. Which makes the XMLConvert class pointed out in the accepted answer an even better alternative.

like image 40
mdb Avatar answered Oct 07 '22 03:10

mdb