modifyManifest
修改 Android Manifest 文件,使用 XPath 语法定位和修改 AndroidManifest.xml 中的元素。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.existsSync | FileSystem['existsSync'] | 检查文件是否存在 |
deps.readFileSync | FileSystem['readFileSync'] | 读取文件内容 |
deps.writeFileSync | FileSystem['writeFileSync'] | 写入文件内容 |
deps.xmlParser | XMLParserConstructor | XML 解析器构造函数 |
deps.xmlSerializer | XMLSerializerConstructor | XML 序列化器构造函数 |
deps.xpath | XPath | XPath 查询库 |
环境要求
- 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 }
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
manifestPath | string | 是 | AndroidManifest.xml 文件路径 |
modifications | ManifestModification[] | 是 | 修改操作数组 |
deps | ModifyManifestDeps | 是 | 依赖注入对象 |
返回值
| 类型 | 说明 |
|---|---|
Promise<ModificationResult> | Promise,解析为修改结果对象 |
工作原理
读取和解析 XML:
- 使用
readFileSync读取 AndroidManifest.xml - 使用 XML 解析器解析为 DOM 文档
- 使用
遍历修改操作: 对每个 ManifestModification:
- 使用 XPath 选择器定位目标元素
- 根据 action 类型执行操作:
setAttribute: 设置元素属性setTextContent: 设置元素文本内容addElement: 添加新的子元素removeElement: 删除元素
序列化和写入:
- 使用 XML 序列化器将 DOM 转换回 XML 字符串
- 写入回 AndroidManifest.xml 文件
返回结果:
- 成功:
success: true,data.modificationsApplied为应用的修改数量 - 失败:
success: false,error包含错误信息
- 成功:
支持批量修改,所有操作在一次读写中完成,提高效率并保持文件一致性。