PowerShell通过XmlDocument类实现XML创建与修改,先创建对象并添加声明、根节点及子节点,再保存为文件;可加载现有文件,用SelectSingleNode查找节点,SetAttribute设置属性,InnerText修改内容,SelectNodes遍历节点,支持XPath查询,还可使用Here-String快速生成简单XML。

在PowerShell中创建和修改XML文件非常方便,因为PowerShell原生支持.NET的System.Xml.XmlDocument类,可以直接操作XML结构。下面介绍常用方法和命令,帮助你轻松实现XML的创建、读取、修改和保存。
使用XmlDocument对象可以新建一个XML文档:
# 创建一个新的XmlDocument对象
$xmlDoc = New-Object System.Xml.XmlDocument
<h1>创建XML声明(可选)</h1><p>$xmlDeclaration = $xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", $null)
$xmlDoc.AppendChild($xmlDeclaration) | Out-Null</p><h1>创建根节点</h1><p>$root = $xmlDoc.CreateElement("Configuration")
$xmlDoc.AppendChild($root) | Out-Null</p><h1>添加子节点</h1><p>$child = $xmlDoc.CreateElement("Setting")
$child.SetAttribute("Name", "Timeout")
$child.InnerText = "30"
$root.AppendChild($child) | Out-Null</p><h1>保存到文件</h1><p>$xmlDoc.Save("C:\temp\config.xml")</p>执行后会在指定路径生成如下内容的XML文件:
<?xml version="1.0" encoding="UTF-8"?><Configuration><Setting Name="Timeout">30</Setting></Configuration>
如果已有XML文件,可以先加载再进行修改:
# 加载现有XML文件
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.Load("C:\temp\config.xml")
<h1>查找节点并修改值</h1><p>$node = $xmlDoc.SelectSingleNode("//Setting[@Name='Timeout']")
if ($node) {
$node.InnerText = "60"
}</p><h1>添加新节点</h1><p>$newNode = $xmlDoc.CreateElement("Setting")
$newNode.SetAttribute("Name", "LogLevel")
$newNode.InnerText = "Info"
$xmlDoc.Configuration.AppendChild($newNode) | Out-Null</p><h1>保存更改</h1><p>$xmlDoc.Save("C:\temp\config.xml")</p>以下是一些常用的PowerShell XML操作方式:
示例:遍历所有Setting节点
$nodes = $xmlDoc.SelectNodes("//Setting")
foreach ($n in $nodes) {
Write-Host "Name: $($n.Name), Value: $($n.InnerText)"
}
对于结构简单的XML,也可以用Here-String快速生成:
[xml]$xml = @"
<?xml version="1.0"?>
<Users>
<User Id="1" Name="Alice" />
<User Id="2" Name="Bob" />
</Users>
"@
<h1>修改第一个用户的名称</h1><p>$xml.Users.User[0].Name = "Alicia"</p><h1>保存</h1><p>$xml.Save("C:\temp\users.xml")</p>基本上就这些。PowerShell处理XML灵活且强大,关键是掌握XmlDocument的基本方法和XPath查询语法。只要会创建、查找、修改、保存节点,就能应对大多数配置文件管理需求。
以上就是如何在PowerShell中创建和修改xml文件 PowerShell的xml操作命令的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号