tadija / AEXML

Swift minion for simple and lightweight XML parsing
MIT License
1.01k stars 200 forks source link

Parser doesn't handle "0" or "1" for Booleans #169

Closed wilmot closed 3 years ago

wilmot commented 4 years ago

According to https://www.w3schools.com/xml/schema_dtypes_misc.asp: "Legal values for boolean are true, false, 1 (which indicates true), and 0 (which indicates false)." Swift's Bool() returns nil for 1 and 0 so we can't use it.

I propose adding code something like the following in Element.swift:

    /// Boolean representation of `value` property (`nil` if `value` can't be represented as Bool).
    open var bool: Bool? {
        if string == "true" || string == "1" { return true }
        if string == "false" || string == "0" { return false }
        return nil
    }

And adding tests for the 0 & 1 case in plant_catalog.xml and AEXMLTests.swift:

    <PLANT>
        <COMMON>Bloodroot</COMMON>\n\t
        <BOTANICAL>Sanguinaria canadensis</BOTANICAL>
        <ZONE>4</ZONE>
        <LIGHT>Mostly Shady</LIGHT>
        <PRICE>2.44</PRICE>
        <AVAILABILITY>031599</AVAILABILITY>
        <TRUESTRING>true</TRUESTRING>
        <FALSESTRING>false</FALSESTRING>
        <TRUEINT>1</TRUEINT>
        <FALSEINT>0</FALSEINT>
        <ELEMENTWITHOUTVALUE></ELEMENTWITHOUTVALUE>
        <EMPTYELEMENT />
    </PLANT>
    func testBoolValue() {
        let firstTrueString = plantsDocument.root["PLANT"]["TRUESTRING"].bool
        XCTAssertEqual(firstTrueString, true, "Should be able to cast element value as Bool.")

        let firstFalseString = plantsDocument.root["PLANT"]["FALSESTRING"].bool
        XCTAssertEqual(firstFalseString, false, "Should be able to cast element value as Bool.")

        let firstTrueInt = plantsDocument.root["PLANT"]["TRUEINT"].bool
        XCTAssertEqual(firstTrueInt, true, "Should be able to cast element value as Bool.")

        let firstFalseInt = plantsDocument.root["PLANT"]["FALSEINT"].bool
        XCTAssertEqual(firstFalseInt, false, "Should be able to cast element value as Bool.")

        let firstElementWithoutValue = plantsDocument.root["ELEMENTWITHOUTVALUE"].bool
        XCTAssertNil(firstElementWithoutValue, "Should be able to return nil if value can't be represented as Bool.")
    }
tadija commented 3 years ago

Added with #170 in 4.6.0.