无法在容器视图中加载xml数据

时间:2017-08-25 16:38:03

标签: ios xml swift xml-parsing iteration

我正在尝试使用XMLParser解析XML URL。这是示例文件:

<itemlist>
<item name="Wave" id="1345" working="YES" extra="abcdef"/>
<item name="SCOOP" id="7585" working="YES" extra="sdgsdga"/>
<item name="Alpha" id="3983" working="NO" extra="jkbk"/>
<item name="panda" id="0237" working="YES" extra="adjkbvd"/>
<item name="ANT" id="7483" working="NO" extra="lnvdnlvs"/>
<item name="Wave!" id="9283" working="YES" extra="hiofenl"/>
<item name="o8" id="9473" working="NO" extra="lacknl"/>
<item name="Enjoy" id="8503" working="NO" extra="dnlk"/>
<item name="89" id="8383" working="YES" extra="nklvdnl"/>
<item name="Hub" id="0023" working="NO" extra="vdnlk"/>
</itemlist>

我能够解析XML文件并可以在控制台中查看数据,但只能在容器视图上加载一个单元格。这是我的代码:

func beginParsing() {

    guard let url = URL(string: "http://example.com/") else { return }

    let parser = XMLParser(contentsOf: url)
    parser?.delegate = self
    parser?.parse()
    self.collectionView?.reloadData()
}

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

    self.items = [Items]()

    if elementName == "item" {
        let item = Items()
        if let name = attributeDict["name"] {
            item.nameLabel = name
            print(item)
        }
        if let itemWorking = attributeDict["working"] {
            item.itemWorkingLabel = itemWorking
            print(itemWorking)
        }
        if let itemId = attributeDict["id"] {
            item.idLabel = itemId
            print(itemId)
        }
        if let itemExtra = attributeDict["extra"] {
            item.extraLabel = itemExtra
            print(itemExtra)
        }

        self.items?.append(item)
    }
}

func parser(_ parser: XMLParser, foundCharacters string: String) {
    self.foundCharacters += string
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "item" {
        let item1 = Item()
        self.items?.append(item1)
        self.items?.removeLast()
    }
    self.foundCharacters = ""
}

func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
    print("failure: ", parseError)
}

以下是模拟器显示的内容: simulator

我该如何解决?感谢。

1 个答案:

答案 0 :(得分:0)

您解决的每个元素(self.items = [Items]())上的问题都是重新启动didStartElement

您还要删除下一行添加的项目:

    self.items?.append(item1)
    self.items?.removeLast()