modifyXml
通用的 XML 文件修改函数,支持修改元素的文本内容或属性值。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.existsSync | FileSystem['existsSync'] | 检查文件是否存在 |
deps.readFileSync | FileSystem['readFileSync'] | 读取文件内容 |
deps.writeFileSync | FileSystem['writeFileSync'] | 写入文件内容 |
deps.xmlParser | XMLParserConstructor | XML 解析器构造函数 |
deps.xmlSerializer | XMLSerializerConstructor | XML 序列化器构造函数 |
环境要求
- @xmldom/xmldom: XML DOM 解析库
bash
npm install @xmldom/xmldom函数签名
typescript
function modifyXml(
xmlFilePath: string,
keyValuePairs: Record<string, string>,
options: XmlModifyOptions,
deps: ModifyXmlDeps
): Promise<{ success: boolean; error?: string }>
interface XmlModifyOptions {
tagName: string // 要查找的元素标签名
matchAttribute: string // 匹配元素的属性名
modifyType: 'textContent' | 'attribute' // 修改类型
targetAttribute?: string // 要修改的属性名(modifyType 为 'attribute' 时)
}
interface ModifyXmlDeps {
existsSync: FileSystem['existsSync']
readFileSync: FileSystem['readFileSync']
writeFileSync: FileSystem['writeFileSync']
xmlParser: XMLParserConstructor
xmlSerializer: XMLSerializerConstructor
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
xmlFilePath | string | 是 | XML 文件路径 |
keyValuePairs | Record<string, string> | 是 | 要修改的键值对 |
options.tagName | string | 是 | 要查找的元素标签名 |
options.matchAttribute | string | 是 | 用于匹配元素的属性名 |
options.modifyType | 'textContent' | 'attribute' | 是 | 修改类型 |
options.targetAttribute | string | 否 | 要修改的属性名(仅当 modifyType 为 'attribute') |
deps | ModifyXmlDeps | 是 | 依赖注入对象 |
返回值
| 类型 | 说明 |
|---|---|
Promise<{ success: boolean; error?: string }> | Promise,解析为修改结果对象 |
异常
| 错误类型 | 触发条件 | 说明 |
|---|---|---|
| 文件不存在 | XML 文件路径无效 | success: false, error 为 "XML文件不存在" |
| 解析失败 | XML 格式错误 | success: false, error 为 "XML文件解析失败" |
工作原理
检查文件:验证 XML 文件是否存在
读取和解析:
- 读取 XML 文件内容
- 使用 XML 解析器解析为 DOM 文档
- 检查是否有解析错误
查找和修改元素:
- 使用
getElementsByTagName查找指定标签的所有元素 - 遍历每个键值对(key, value)
- 对每个元素,检查其
matchAttribute属性值是否等于 key - 匹配成功时:
modifyType = 'textContent': 设置元素的textContentmodifyType = 'attribute': 设置元素的targetAttribute属性值
- 使用
序列化和写入:
- 使用 XML 序列化器将 DOM 转换回 XML 字符串
- 写入回原文件
返回结果:
- 成功:
success: true - 失败:
success: false, 包含错误信息
- 成功:
支持批量修改,通过 matchAttribute 精确匹配目标元素。