ios - 在 Swift 中解析 XML 文件

标签 ios xml swift

我正在尝试使用 NSXMLParser 解析 XML 文件。最初一切似乎都工作正常,但内容结果似乎被截断并得到了一些奇怪的结果。

func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
    if elementName == "title" {
        foundTitle = true
    }

    if elementName == "description" {
        foundDescription = true
    }
}

func parser(parser: NSXMLParser!, foundCharacters string: String!) {
    if (foundItem) {
        if foundTitle {
            println("Title: \(string)")
            foundTitle = false
        }
        else if foundDescription {
            println("Description: \(string)")
            foundDescription = false
        }
    }
}

我正在测试的 RSS 提要是科技历史上的这一天 ( http://feedpress.me/ThisDayInTechHistory ),现在第一条新闻如下:

Title: IBM’s First Desktop Computer
Description: IBM introduces their System/23 Datamaster desktop computer...

对于我的测试结果,这就是我得到的:

Title: IBM
Description: ’s First Desktop Computer
Description: July 28, 1981 IBM introduces their System/23 Datamaster desktop computer...

请注意,标题在第一个 ' 之后被截断并成为描述!这是 NSXMLParser 中的错误吗?或者我做错了什么?谢谢!

最佳答案

你的猜测是正确的! NSXMLParser 假设字符串已经被转义,并且会遇到包含 > 在内的字符的问题。 , < , ' , & ,和\ .

要对字符串进行全局替换,您可以使用 NSString方法stringByReplacingOccurrencesOfString ,像这样:

let xml = "<desciption>Here's a malformed XML string. Ain't it ugly?</description>"
xml.stringByReplacingOccurrencesOfString("'", withString: "&quot;")

返回结果:

"<desciption>Here&quot;s a malformed XML string. Ain&quot;t it ugly?</description>"

关于ios - 在 Swift 中解析 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25007440/

相关文章:

ios - 使用没有属性名称的 RestKit 映射 JSON

ios - NSDateFormatter为2015-02-13 17:16:00 +0000

c# - 在 .NET 中循环遍历 XML?

java - 在 JAXB 中控制 namespace 前缀

ios - 应用程序在 iPhone 上测试时崩溃,但在模拟器中没有

ios - 我如何解析这个 JSON Pokemon 字典? Sprite 宝可梦 API (swift 3)

iphone - 使用indexOfObject :inSortedRange:options:usingComparator:对数组进行二分搜索

iOS 7 通知中心像标签

mysql - 如何将存储在 XML 文件中的数据转换成关系数据库(MySQL)?

swift - Swift 中的迭代中序遍历错误答案