问题描述
使用Swift/cocoa,我正在创建一个用户输入表单,该表单将输出一个XML文件. (以上所有内容的入门.)
Using Swift/cocoa I am creating a user input form that will output an XML file. (Beginner to all the above.)
用户将添加多个目标,但是尝试创建多个目标"时出现错误.
The user will be adding multiple targets but I am getting an error when trying to create multiple 'targets.'
流程为:用户输入要创建的目标数(7、8或9).每个目标都有用户输入的信息,因此有"x"个目标.我使用for循环,但是在尝试创建下一个目标时遇到错误.下面是我在操场上的代码.
The flow is: User enters the number of targets they want to create (7,8. or 9). Each target has information that the user enters, so there are 'x' number of targets. I use a for loop but am getting an error when trying to create the next target. Below is my code from the playground.
(如果我取消注释//expedition.addChild(target),则会收到错误消息.)
(If I uncomment //expedition.addChild(target) I receive an error.)
如何创建这些多个目标孩子?
How do I create these multiple target children?
let root = NSXMLElement(name: "exploration_game")
let xmlFile = NSXMLDocument (rootElement: root)
let expedition = NSXMLElement(name: "expedition")
root.addChild(expedition)
expedition.addChild(NSXMLElement(name: "name", stringValue: ""))
expedition.addChild(NSXMLElement(name: "targets", stringValue: ""))
expedition.addChild(NSXMLElement(name: "difficulty", stringValue: ""))
expedition.addChild(NSXMLElement(name: "factoid", stringValue: ""))
expedition.addChild(NSXMLElement(name: "factoid_file", stringValue: ""))
let target = NSXMLElement(name: "target")
expedition.addChild(target)
for index in 1...3{
//expedition.addChild(target)
target.addChild(NSXMLElement(name: "target_title_en", stringValue: ""))
target.addChild(NSXMLElement(name: "target_title_sp", stringValue: ""))
target.addChild(NSXMLElement(name: "target_hint_en", stringValue: ""))
target.addChild(NSXMLElement(name: "target_hint_sp", stringValue: ""))
target.addChild(NSXMLElement(name: "target_description_en", stringValue: ""))
target.addChild(NSXMLElement(name: "target_descriptionsp", stringValue: ""))
target.addChild(NSXMLElement(name: "x", stringValue: ""))
target.addChild(NSXMLElement(name: "y", stringValue: ""))
target.addChild(NSXMLElement(name: "target_icon", stringValue: ""))
target.addChild(NSXMLElement(name: "target_somethin", stringValue: ""))
}
非常感谢您的帮助.
推荐答案
您没有在循环中创建新目标.显然,如果要向远征中添加多个目标,则需要为每个迭代创建一个新目标.
You are not creating a new target in the loop. Obviously you need to create a new target for each iteration if you want to add more than one target to an expedition.
// set up expedition
for _ in 1...3 {
var target = NSXMLElement(name: "target")
// configure target
expedition.addChild(target)
}
这篇关于Swift NSXML需要循环以创建多个子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!