近来项目需要,生成XML字符串,又不想拼接和用别的三方库,然后就各种搜索百度和ai,记录一下
let doc = xmlNewDoc(XML_DEFAULT_VERSION)
//创建根节点 label
let rootNode = xmlNewNode(nil, "label")!
xmlDocSetRootElement(doc, rootNode)
//创建子节点
let headerNode = xmlNewChild(rootNode, nil, "header", nil)
xmlNewChild(headerNode, nil, "ModelId", header.ModelId)
//获取XML字符串
//https://stackoverflow.com/questions/4155730/creating-string-with-libxml2-c
var buffer: UnsafeMutablePointer<xmlChar>?
var size: Int32 = 0
xmlDocDumpFormatMemoryEnc(doc, &buffer, &size, "UTF-8", 0) //format 0 无格式, 1 带格式
let xmlString = String(cString: UnsafePointer(buffer!))
print(xmlString)
xmlFree(buffer)
xmlFreeDoc(doc)