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

在PowerShell中创建和修改XML文件非常方便,因为PowerShell原生支持.NET的System.Xml.XmlDocument类,可以直接操作XML结构。下面介绍常用方法和命令,帮助你轻松实现XML的创建、读取、修改和保存。
创建新的XML文件
使用XmlDocument对象可以新建一个XML文档:
# 创建一个新的XmlDocument对象 $xmlDoc = New-Object System.Xml.XmlDocument创建XML声明(可选)
$xmlDeclaration = $xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", $null) $xmlDoc.AppendChild($xmlDeclaration) | Out-Null
创建根节点
$root = $xmlDoc.CreateElement("Configuration") $xmlDoc.AppendChild($root) | Out-Null
添加子节点
$child = $xmlDoc.CreateElement("Setting") $child.SetAttribute("Name", "Timeout") $child.InnerText = "30" $root.AppendChild($child) | Out-Null
保存到文件
$xmlDoc.Save("C:\temp\config.xml")
执行后会在指定路径生成如下内容的XML文件:
30
加载并修改现有XML文件
如果已有XML文件,可以先加载再进行修改:
# 加载现有XML文件
$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.Load("C:\temp\config.xml")
查找节点并修改值
$node = $xmlDoc.SelectSingleNode("//Setting[@Name='Timeout']")
if ($node) {
$node.InnerText = "60"
}
添加新节点
$newNode = $xmlDoc.CreateElement("Setting")
$newNode.SetAttribute("Name", "LogLevel")
$newNode.InnerText = "Info"
$xmlDoc.Configuration.AppendChild($newNode) | Out-Null
保存更改
$xmlDoc.Save("C:\temp\config.xml")
常用XML操作命令与技巧
以下是一些常用的PowerShell XML操作方式:
- SelectSingleNode():通过XPath查找单个节点
- SelectNodes():返回匹配的节点集合
- CreateElement():创建新元素
- CreateAttribute():创建属性
- SetAttribute():设置元素属性值
- RemoveChild():删除子节点
- InnerText:获取或设置节点文本内容
示例:遍历所有Setting节点
$nodes = $xmlDoc.SelectNodes("//Setting")
foreach ($n in $nodes) {
Write-Host "Name: $($n.Name), Value: $($n.InnerText)"
}
直接使用Here-String快速创建简单XML(可选)
对于结构简单的XML,也可以用Here-String快速生成:
[xml]$xml = @""@ 修改第一个用户的名称
$xml.Users.User[0].Name = "Alicia"
保存
$xml.Save("C:\temp\users.xml")
基本上就这些。PowerShell处理XML灵活且强大,关键是掌握XmlDocument的基本方法和XPath查询语法。只要会创建、查找、修改、保存节点,就能应对大多数配置文件管理需求。










