如何用PowerShell修改Android字符串资源XML,将条目值替换为名称?
优化PowerShell编辑Android字符串资源XML的脚本实现
需求概述
- 将XML中每个
<string>标签的文本内容替换为自身的name属性值 - 将
<plurals>标签下所有<item>的文本内容替换为对应<plurals>的name属性值
原始XML内容
<?xml version="1.0" encoding="UTF-8"?> <resources> <plurals name="test1"> <item quantity="one">%d hello</item> <item quantity="other">%d work</item> </plurals> <string name="test2">house</string> <string name="test3">horse</string> </resources>
期望修改后的XML内容
<resources> <plurals name="test1"> <item quantity="one">test1</item> <item quantity="other">test1</item> </plurals> <string name="test2">test2</string> <string name="test3">test3</string> </resources>
你编写的原始脚本
param() $fileName = "string.xml" $repoFile = $fileName "Script start!" if(!(Test-Path $repoFile)) { "warning: $repoFile was not found!" continue } $root = [xml](Get-Content $repoFile) "Plurals" foreach ($plural in $root.resources.plurals) { foreach ($node in $plural.item){ $node.InnerText= [string]$plural.name } } "Strings" foreach ($node in $root.resources.string) { $node.InnerText= [string]$node.name } $root.Save($fileName)
更优的实现方案
你的原始脚本已经能完成核心需求,但可以从健壮性、灵活性、可读性三个维度优化,以下是改进后的版本:
param( [string]$fileName = "strings.xml" # 支持通过参数指定目标文件,提升复用性 ) Write-Host "脚本启动!" # 检查文件是否存在 if (-not (Test-Path $fileName)) { Write-Warning "警告:未找到目标文件 $fileName!" exit 1 # 用exit终止脚本,原脚本的continue无意义 } try { # 用-Raw一次性读取完整内容,避免分段读取导致的XML解析错误;指定UTF8编码保证兼容性 $xmlContent = Get-Content $fileName -Raw -Encoding UTF8 $xml = [xml]$xmlContent } catch { Write-Error "XML解析失败:$_" exit 1 } # 处理plurals节点 Write-Host "正在处理plurals节点..." foreach ($plural in $xml.resources.plurals) { $targetName = $plural.name foreach ($item in $plural.item) { $item.InnerText = $targetName } } # 处理string节点 Write-Host "正在处理string节点..." foreach ($stringNode in $xml.resources.string) { $stringNode.InnerText = $stringNode.name } # 保存修改后的文件 try { $xml.Save((Resolve-Path $fileName).Path) Write-Host "修改完成,已保存到 $fileName" } catch { Write-Error "文件保存失败:$_" exit 1 }
核心优化点说明
- 参数化配置:通过
param定义可选参数,允许运行脚本时指定不同的文件名,无需修改脚本内容 - 编码与读取优化:使用
-Raw读取完整XML内容,避免因分段读取导致的解析异常;指定UTF8编码适配Android资源文件的编码规范 - 错误处理增强:添加
try/catch捕获XML解析和文件保存过程中的异常,避免脚本意外崩溃并给出明确错误提示 - 输出规范:用
Write-Host/Write-Warning/Write-Error区分不同类型的输出信息,可读性更强 - 逻辑简化:去掉冗余的
$repoFile变量,直接使用$fileName,代码更简洁
内容的提问来源于stack exchange,提问作者aeroxr1
相关产品推荐
相关产品推荐

