1

I tried to parse a let contentString = "<p>abcdefg</p><p>hijklmn</p><p>123456</p>", which are html tags, with XMLParser.
When I print elementName and content between tag in XMLParserDelegate methods, only the first tag(p, abcdefg) was printed.

let contentString = "<p>abcdefg</p><p>hijklmn</p><p>123456</p>"
if let data = contentString.data(using: .utf8) {
    let parser = XMLParser(data: data)
    parser.parse()
}

XMLParserDelegate methods

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
    print(elementName)
}

func parser(_ parser: XMLParser, foundCharacters string: String) {
    print(string)
}

console log
p
abcdefg

I don't know why parser stop parsing at first tag(p)

0

1 Answer 1

1

There are many problems with your code, but the main one here is that your contentString is not valid XML. Because of that, there's no good way to tell the XMLParser to parse the whole string.

(Actually I'm quite impressed with what it did. Instead of choking, it parsed up until the validity of the XML ended, and then stopped.)

Valid XML must consist of a single root element; for example

<root><p>abcdefg</p><p>hijklmn</p><p>123456</p></root>

Once you have modified your XML to be valid, you will need to think about how to deal with the delegate so as to parse that XML. But that's a different matter.

Sign up to request clarification or add additional context in comments.

2 Comments

It worked after adding a root element to contentString. Thanks. Can you be more specific about many problems except the main one?
Well, for example, it's quite possible that foundCharacters will be called many times for a single text node. Your code needs to be prepared for that. And of course the policy of declaring a single delegate for the parser makes parsing more elaborate hierarchies harder.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.