格式化数据以写入XML的最佳方法

时间:2016-07-31 21:46:37

标签: xml macos swift2

我想创建一个这样的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 writeToXMLDoc: 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中更具可读性?有没有办法在Xcode项目中创建一个单独的XML格式的文件?怎么做?

如果可以创建单独的文件,如何为x和y提供变量?

1 个答案:

答案 0 :(得分:1)

您的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>