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

z18hc3ub  于 2023-04-30  发布在  Swift
关注(0)|答案(1)|浏览(320)

我想创建一个像这样的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格式的文件?
如何输入XY坐标值?

kd3sttzy

kd3sttzy1#

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>

相关问题