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
<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><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2079" title="SumiNote"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680172275549.png" alt="SumiNote" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2079" title="SumiNote">SumiNote</a>
<p>一款服务留学生的AI学习神器</p>
</div>
<a href="/ai/2079" title="SumiNote" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>执行后会在指定路径生成如下内容的XML文件:
<?xml version="1.0" encoding="UTF-8"?><Configuration><Setting Name="Timeout">30</Setting></Configuration>
加载并修改现有XML文件
如果已有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>常用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 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查询语法。只要会创建、查找、修改、保存节点,就能应对大多数配置文件管理需求。









