繁体   English   中英

使用 powershell 编辑 XML ID 值

[英]Edit XML ID value with powershell

如何为 XML 文件设置值? 这是我的 XML 文件:

<?xml version="1.0"?>
-<settings version="2">
<setting id="noteid">266</setting>
</settings>

这是我的代码,但它不起作用

$filePath = 'C:\Users\EA\Desktop\settings.xml '
$xml=New-Object XML
$xml.Load($filePath)
$nodes = $xml.SelectNodes('/settings/noteid');
foreach($node in $nodes)
{
$node.SetAttribute('type', '1234');
}
$xml.Save($filePath)

做了一些搜索,但对我没有任何作用。 任何的想法?

假设您的 XML 文件如下所示:

<?xml version="1.0"?>
<settings version="2">
    <setting id="noteid">266</setting>
</settings>

并且您知道要更改值的位置,可以使用点表示法访问您要访问的特定节点:

$filePath = 'C:\Users\EA\Desktop\settings.xml'
[XML]$xml = Get-Content -Path $filePath

$xml.settings.setting.'#text' = '12345'

$xml.Save($filePath)

如果我理解正确的话,您已经给了我们一个非常简短的 XML 外观示例,因此我在此处对其进行了扩展:

<?xml version="1.0"?>
<settings version="2">
    <setting id="noteid">266</setting>
    <setting id="someotherid">12345</setting>
    <setting id="anothersettingsid">987</setting>
</settings>

您可以使用 'dot'(不区分大小写)方法更改 id 为 'noteid' 的设置值,如下所示:

$newNoteId = 987654321
$filePath  = 'C:\Users\EA\Desktop\settings.xml'
[xml]$xml  = Get-Content -Path $filePath -Raw

($xml.settings.setting | Where-Object { $_.id -eq 'noteid' }).InnerText = $newNoteId

$xml.Save($filePath)

或者使用 XPath(记住这是区分大小写的..)

$newNoteId = 987654321
$filePath  = 'C:\Users\EA\Desktop\settings.xml'
[xml]$xml  = Get-Content -Path $filePath -Raw

$xml.SelectNodes('//setting[@id="noteid"]') | ForEach-Object { $_.InnerText = $newNoteId }

$xml.Save($filePath)

在这两种情况下,结果都是:

<?xml version="1.0"?>
<settings version="2">
  <setting id="noteid">987654321</setting>
  <setting id="someotherid">12345</setting>
  <setting id="anothersettingsid">987</setting>
</settings>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM