【问题标题】:Swift - created parse nested xml issueSwift - 创建解析嵌套 xml 问题
【发布时间】:2017-03-11 19:18:58
【问题描述】:

我正在尝试解析 XML 并希望在表格视图中显示数据。如果 XML 中有 4 个 ListSections 标签,那么表格视图将有 4 个部分,每个部分将根据数据显示行。每个 ListSection 标签都有多个 Team 标签。我想根据部分显示这些团队。

这是我的 XML 结构。

 <List>
   <ListSection sectionName="section 1">
      <Team id="10" name="Team1">
          <OppositeTeam oppName="TeamX" day="Monday"/>
      </Team>
      <Team id="20" name="Team2">
          <OppositeTeam oppName="TeamY" day="Tuesday"/>
      </Team>
   </ListSection> 
   <ListSection sectionName="section 2">
      <Team id="100" name="Team100">
          <OppositeTeam oppName="TeamA" day="Monday"/>
      </Team>
      <Team id="200" name="Team200">
          <OppositeTeam oppName="TeamB" day="Monday"/>
      </Team>
   </ListSection> 
 </List>

我正在尝试为此 xml 创建模型类。 到目前为止,我已经创建了 2 个类。

class ListSection {
  var sectionName: String = String()
  var team : [Team] = []
}

class Team {
  var teamId:String = String()
  var teamName:String = String()
} 

我不确定我创建的这个数据模型。如果我朝正确或错误的方向前进,任何人都可以建议我吗?

提前致谢。

更新: 这是我的 Swift 解析代码。我无法将数据保存在适当的对象中。

var listSection: [ListSection] = []
var teamArray : [Team] = []
var teamData = NSMutableArray()

var sectionName = String()
var teamName = String()

var listSectionObj = ListSection()

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

    if elementName == "ListSection" {
        listSectionObj = ListSection()
        listSectionObj.sectionName = ""
        listSectionObj.team = [] 
        if let sectionName = attributeDict["sectionName"] as String? {
            self. sectionName = sectionName
        }
    }else if elementName == "Team" {
         if let teamName = attributeDict["TeamName"] as String? {
            self.teamName = teamName
        }
    }
}


func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "ListSection" {

        listSectionObj.sectionName = sectionName
        listSection.append(listSectionObj)
    }else if elementName == "Team" {
        teamObj = Team()
        teamObj.teamName = teamName
        teamArray.append(teamObj)
        print("teamArray = \(teamArray)") 
    }
}

【问题讨论】:

    标签: ios swift data-structures nsxmlparser


    【解决方案1】:

    我不确定你的意思是你不能在对象中保存数据,但是如果你想存储自定义对象,我强烈建议你看看这个:http://nshipster.com/nscoding/

    另外,根据 XML 结构,您的数据结构看起来不错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多