What to do in case of an error when parsing xml with swift?

Asked 1 months ago, Updated 1 months ago, 3 views

Currently, I am creating an application that parses xml in NSXMLParser and displays it in tableview.There is no problem if xml can be retrieved successfully, but I am having trouble knowing how to check if there are errors (such as incorrect parameters at the time of request or zero).
The following is an example of an applicable case.
In the case below, there seems to be no parserDidStartDocument or parseErrorOccurred action.

<root>error>wrong_parameter</error_description>specify valid applicationId</error_description>

I'd like to check if the response contains errors, but what should I do?

swift xml

2022-09-30 11:13

1 Answers

Because the string you provided is completely correct as XML, the library side does not report errors, whether it is an NSXMLParser or any other XML parsing library.(By the way, if delete is set correctly, parserDidStartDocument is called.)

If you want to treat such XML as an error, you need to define exactly what XML should be treated as an error and program it as logic yourself.

For example, if you say "any hierarchy of error elements will be treated as errors," you will decide within parser(_:didStartElement:namespaceURI:qualifiedName:attributes:)

class MyXMLParser:NSObject, NSXMLParserDelegate{
    let parser —NSXMLParser

    //...

    func parser(parser:NSXMLParser, didStartElementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
        if elementName=="error" {
            print("found error")
            parser.abortParsing()
        }
        // What to do if you find a start tag other than an error element?
        //...
    }
}

First, identify the error case and the normal case, and consider what XML should be treated as an error.


2022-09-30 11:13

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.