我想创建一个这样的 XML 文档:
<prefs>
<exactmap>
<map>
(UCS point_1 : x = 50.0, y = 50.0)
(UCS point_2 : x = 300.0, y = 200.0)
(UCS point_3 : x = 200.0, y = 400.0)
(UCS point_4 : x = 300.0, y = 300.0)
</map>
</exactmap>
</prefs>
到目前为止我的代码(表达式)看起来一团糟:
let writeToXML: NSString = "<prefs>\n\t<exactmap>\n\t\t<map>\n\t\t\t//(UCS point_1 : x = 50.0, y = 50.0 )\n\t\t\t(UCS point_2 : x = 300.0, y = 200.0 )\n\t\t\t(UCS point_3 : x = 200.0, y = 400.0 )\n\t\t\t(UCS point_4 : x = 300.0, y = 300.0 )\n\t\t</map>\n\t</exactmap>\n</prefs>"
如何使用 Swift 生成 XML 格式的文件?
如何为
X
和Y
坐标输入值?
你的 XML 结构是错误的。您将如何从 XML 文件中读回?您的数据现在已变得非结构化。
玩下面的代码。它很长,因为它是XM(悲伤)
func xmlAttributeWithName(name: String, value: String) -> NSXMLNode {
let node = NSXMLNode(kind: .AttributeKind)
node.name = name
node.stringValue = value
return node
}
// Your data
let points = [
(x: 50.0, y: 50.0),
(x: 300.0, y: 200.0),
(x: 200.0, y: 400.0),
(x: 300.0, y: 300.0)
]
let mapElement = NSXMLElement(name: "map")
for (index, p) in points.enumerate() {
let pointElement = NSXMLElement(name: "ucs_point")
pointElement.attributes = [
xmlAttributeWithName("id", value: "\(index)"),
xmlAttributeWithName("x", value: "\(p.x)"),
xmlAttributeWithName("y", value: "\(p.y)")
]
mapElement.addChild(pointElement)
}
let exactMapElement = NSXMLElement(name: "exactmap")
exactMapElement.addChild(mapElement)
let prefsElement = NSXMLElement(name: "prefs")
prefsElement.addChild(exactMapElement)
let xmlDocument = NSXMLDocument(rootElement: prefsElement)
xmlDocument.characterEncoding = "utf-8"
xmlDocument.version = "1.0"
let xmlOptions = NSXMLNodePrettyPrint | NSXMLNodeCompactEmptyElement
let xmlString = xmlDocument.XMLStringWithOptions(xmlOptions)
try! xmlString.writeToFile("/path/to/file.xml", atomically: true, encoding: NSUTF8StringEncoding)
结果:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<prefs>
<exactmap>
<map>
<ucs_point id="0" x="50.0" y="50.0"/>
<ucs_point id="1" x="300.0" y="200.0"/>
<ucs_point id="2" x="200.0" y="400.0"/>
<ucs_point id="3" x="300.0" y="300.0"/>
</map>
</exactmap>
</prefs>