Skip to content

modifyManifest

修改 Android Manifest 文件,使用 XPath 语法定位和修改 AndroidManifest.xml 中的元素。

前置依赖

依赖参数

参数名类型说明
deps.existsSyncFileSystem['existsSync']检查文件是否存在
deps.readFileSyncFileSystem['readFileSync']读取文件内容
deps.writeFileSyncFileSystem['writeFileSync']写入文件内容
deps.xmlParserXMLParserConstructorXML 解析器构造函数
deps.xmlSerializerXMLSerializerConstructorXML 序列化器构造函数
deps.xpathXPathXPath 查询库

环境要求

  • fs: Node.js 文件系统模块
  • xpath: XML 路径查询库
  • @xmldom/xmldom: XML DOM 解析库
bash
npm install xpath @xmldom/xmldom

函数签名

typescript
function modifyManifest(
  manifestPath: string,
  modifications: ManifestModification[],
  deps: ModifyManifestDeps
): Promise<ModificationResult>

type ModifyAction = 'setAttribute' | 'setTextContent' | 'addElement' | 'removeElement'

interface ManifestModification {
  xpath: string                // XPath 选择器
  action: ModifyAction         // 操作类型
  attributeName?: string       // 属性名(setAttribute 时使用)
  value?: string               // 属性值或文本内容
  elementName?: string         // 元素标签名(addElement 时使用)
  attributes?: Record<string, string>  // 元素属性(addElement 时使用)
}

interface ModifyManifestDeps {
  existsSync: FileSystem['existsSync']
  readFileSync: FileSystem['readFileSync']
  writeFileSync: FileSystem['writeFileSync']
  xmlParser: XMLParserConstructor
  xmlSerializer: XMLSerializerConstructor
  xpath: XPath
}

interface ModificationResult {
  success: boolean
  message?: string
  error?: string
  data?: { modificationsApplied: number }
}

参数

参数名类型必填说明
manifestPathstringAndroidManifest.xml 文件路径
modificationsManifestModification[]修改操作数组
depsModifyManifestDeps依赖注入对象

返回值

类型说明
Promise<ModificationResult>Promise,解析为修改结果对象

工作原理

  1. 读取和解析 XML

    • 使用 readFileSync 读取 AndroidManifest.xml
    • 使用 XML 解析器解析为 DOM 文档
  2. 遍历修改操作: 对每个 ManifestModification:

    • 使用 XPath 选择器定位目标元素
    • 根据 action 类型执行操作:
      • setAttribute: 设置元素属性
      • setTextContent: 设置元素文本内容
      • addElement: 添加新的子元素
      • removeElement: 删除元素
  3. 序列化和写入

    • 使用 XML 序列化器将 DOM 转换回 XML 字符串
    • 写入回 AndroidManifest.xml 文件
  4. 返回结果

    • 成功:success: true, data.modificationsApplied 为应用的修改数量
    • 失败:success: false, error 包含错误信息

支持批量修改,所有操作在一次读写中完成,提高效率并保持文件一致性。