Swift NSXElement addChild无法将子子级添加到子级

时间:2015-01-08 03:47:24

标签: xml swift nsxmlelement

我正在学习Swift,并希望根据用户输入创建一个xml文件。我能够创建文档根和一个子级别,但不能创建子子级。我不知道我错过了什么。我如何“漂亮地打印”到我的xml?

所需的xml文件输出示例:

<find_sites>
  <name>Many Sites</name>
       <sites>8</sites>
         <site_info>
              <site_name>First Site</site_name>
              <site_description>Description of first site</site_description>
         </site_info>
</find_sites>

我在操场上的Swift Code:

let root = NSXMLElement(name: "find_sites")
let xmlFile = NSXMLDocument (rootElement: root)
root.addChild(NSXMLElement(name: "name", stringValue: "Many Sites"))
root.addChild(NSXMLElement(name: "sites", stringValue: "8"))
let site_info = NSXMLElement(name: "site_info")
root.addChild(NSXMLElement(name: "site_info"))
site_info.addChild(NSXMLElement(name: "site_name", stringValue: "First Site"))
site_info.addChild(NSXMLElement(name: "site_description", stringValue: "Description"))
println(" \(xmlFile.XMLString)")

Results:  <find_sites><name>Many Sites</name><sites>8</sites><site_info></site_info></find_sites>

我的'site_info'的子元素将被忽略。

1 个答案:

答案 0 :(得分:0)

您要将NSXMLElement个新实例添加为root而非site_info的子级。将第6行更改为:

root.addChild(site_info)