Sample code for 30+ languages & platforms
Swift

Demonstrate XML SearchForTag2

Demonstrates how to use SearchForTag2.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let xml = CkoXml()!

    // Load the following XML:

    // 	<Test>
    // 	    <testchild1>
    // 	        test
    // 	    </testchild1>
    // 	    <testchild1>
    // 	        test1
    // 	    </testchild1>
    // 	    <testchild1>
    // 	        test2
    // 	    </testchild1>
    // 	    <testchild1>
    // 	        test3
    // 	    </testchild1>
    // 	    <testchild1>
    // 	        test4
    // 	    </testchild1>
    // 	    <testchild1>
    // 	        test5
    // 	    </testchild1>
    // 	    <testchild1>
    // 	        test6
    // 	    </testchild1>
    // 	</Test>

    success = xml.load(xmlData: "<Test><testchild1>test</testchild1><testchild1>test1</testchild1><testchild1>test2</testchild1><testchild1>test3</testchild1><testchild1>test4</testchild1><testchild1>test5</testchild1><testchild1>test6</testchild1></Test>")

    var i: Int = 0
    var xmlSearch: CkoXml? = xml.getRoot()
    var afterPtr: CkoXml? = xml.getRoot()
    var pTemp: CkoXml?

    // Alway begin the search from the root.
    while xmlSearch!.search(forTag2: afterPtr, tag: "testchild1") {
        // If successful, xmlSearch now points to the found element.
        i = i + 1

        // Set afterPtr = xmlSearch (so we find the next match after the one we just found)
        // Rest xmlSearch to the root of the XML tree to be searched.
        print("\(i): \(xmlSearch!.content!)")
        pTemp = afterPtr
        afterPtr = xmlSearch
        pTemp!.getRoot2()
        xmlSearch = pTemp
    }

    xmlSearch = nil
    afterPtr = nil

    print("----")

    // A better way:
    let sbState = CkoStringBuilder()!
    i = 0
    while xml.next(inTraversal2: sbState) != false {
        if xml.tagEquals(tag: "testchild1") == true {
            print("\(i): \(xml.content!)")
            i = i + 1
        }

    }

    xml.getRoot2()

}