Powershell正在编辑android字符串资源xml文件



我正在用powershell字符串编辑android 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>

<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>

我认为这是可能的,但我不是powershell专家。从零开始,我就这样做了。。有更好的方法吗?:

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)

您可以使用xpath选择器来实现此任务

$root = [xml](Get-Content $repoFile)
# replace text for item node under plurals under resources
$root.selectNodes("/resources/plurals/item") | %{ $_.InnerText = "test1" }
# replace text for string with attribute name = test2 under ressources
$root.selectNodes("/resources/string[@name='test2']") | %{ $_.InnerText = "test2" }
# replace text for string with attribute name = test3 under ressources
$root.selectNodes("/resources/string[@name='test3']") | %{ $_.InnerText = "test3" }

最新更新