You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何在XML文档插入自定义函数生成的元素并另存

Swift原生处理XML插入元素的正确实现

不用第三方库的话,Foundation框架中的XMLDocument是最佳选择——它基于DOM模型,可以直接操作XML节点,完整保留原文档的结构、属性和格式,完美解决你之前遇到的属性丢失、重复插入问题。

核心思路

  1. 用XMLDocument加载原始XML,保留所有原始结构
  2. 通过XPath定位所有<original>元素
  3. 对每个<original>提取内容,调用自定义函数处理
  4. 创建新的<destination>元素,插入到对应<original>的下一个兄弟节点位置
  5. 保存修改后的XML到新文件

完整代码实现

import Foundation

// 自定义处理函数,示例为转大写,可根据需求修改
func doThings(_ input: String) -> String {
    return input.uppercased()
}

// 1. 加载原始XML文件
guard let inputXMLURL = Bundle.main.url(forResource: "input", withExtension: "xml"),
      let xmlData = try? Data(contentsOf: inputXMLURL),
      let xmlDoc = try? XMLDocument(data: xmlData, options: [.nodePreserveWhitespace]) else {
    fatalError("无法加载原始XML文件")
}

// 2. 用XPath查找所有<original>元素
let xpathQuery = "//original"
guard let originalElements = try? xmlDoc.nodes(forXPath: xpathQuery) as? [XMLElement] else {
    fatalError("未找到任何<original>元素")
}

// 3. 逐个处理每个<original>元素
for originalElement in originalElements {
    // 跳过已存在<destination>的情况,避免重复插入
    if let nextSibling = originalElement.nextSibling, nextSibling.name == "destination" {
        continue
    }
    
    // 提取<original>的文本内容(去除首尾空白)
    guard let originalContent = originalElement.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines),
          !originalContent.isEmpty else {
        continue
    }
    
    // 调用自定义函数处理内容
    let processedContent = doThings(originalContent)
    
    // 4. 创建<destination>元素并设置内容
    let destinationElement = XMLElement(name: "destination", stringValue: processedContent)
    
    // 5. 将<destination>插入到<original>的下一个位置
    if let parentNode = originalElement.parent {
        if let originalIndex = parentNode.children?.firstIndex(of: originalElement) {
            parentNode.insertChild(destinationElement, at: originalIndex + 1)
        }
    }
}

// 6. 保存修改后的XML到新文件
let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let outputXMLURL = documentsDir.appendingPathComponent("processed_output.xml")

do {
    // 保存时保留原格式并美化输出
    let outputData = xmlDoc.xmlData(options: [.nodePreserveWhitespace, .nodePrettyPrint])
    try outputData.write(to: outputXMLURL)
    print("处理完成,文件已保存至:\(outputXMLURL.path)")
} catch {
    print("保存文件失败:\(error.localizedDescription)")
}

关键细节说明

  • XMLDocument的优势:不同于SAX解析(XMLParser)只能读不能改,DOM模型允许直接操作节点,完整保留原XML的属性、命名空间、空格和注释
  • XPath定位://original可以快速匹配所有层级的<original>元素,无需手动遍历整个XML树
  • 避免重复插入:通过检查nextSibling是否为<destination>,防止重复处理同一元素
  • 格式保留:加载和保存时使用.nodePreserveWhitespace选项,确保原文档的格式不会被破坏

内容的提问来源于stack exchange,提问作者markb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:35:27