[英]Modify XML from the command line
我有一個結構如下的 xml 文件,我想從命令行編輯這個文件。
<server>
<service>
<Connector port="8080" password="password1234"/>
</service>
</server>
我想更改密碼或端口號。
cmd 提供這個選項還是我需要一個額外的工具? 我知道 PowerShell 可以做到,但這對我來說不是最好的解決方案。 (此外,我沒有使用 powershell 運行它:()。
搜索“password1234”並替換它也可以,因為我的文件中有一個默認密碼,它總是相同的,必須替換它。
為了演示我使用的一種方法,讓我們首先在您的示例中創建 xml 文件:
為 XML 文件名定義變量
$xmlFile = "C:\temp\myconfig.xml"
定義要保存到文件的 XML 字符串
$xmlFromString = [xml]@"
<server>
<service>
<Connector port="8080" password="password1234"/>
</service>
</server>
"@
將xml內容保存到文件中
$xmlFromString.Save($xmlFile)
結果文件內容
Get-Content -Path $xmlFile
<server> <service> <Connector port="8080" password="password1234" /> </service> </server>
這是用於更改值的 PowerShell 代碼 Get XML content from file
$xml = [xml](Get-Content -Path $xmlFile)
查找元素/節點並更改屬性值
$node = $xml.selectSingleNode('//server/service/Connector')
$node.port = "9090"
$node.password = "MyNewPassord4321"
保存 XML 內容
$xml.Save($xmlFile)
結果
Get-Content -Path $xmlFile
<server> <service> <Connector port="9090" password="MyNewPassord4321" /> </service> </server>
將命令保存到 PowerShell ps1 文件並通過 PowerShell 執行/運行它。
我們需要有關您嘗試完成什么的更多詳細信息,例如:
希望這是有幫助的。 - 布魯克斯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.