You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell根据XML子节点值筛选父节点并插入新子元素咨询

PowerShell 实现代码

# 替换为实际的XML文件本地路径
$xmlFilePath = "C:\your\path\catalog.xml"

# 初始化XML对象并加载文件,保留原格式缩进
$xml = New-Object System.Xml.XmlDocument
$xml.PreserveWhitespace = $true
$xml.Load($xmlFilePath)

# 定位author值为Corets, Eva的book节点
$targetBookNode = $xml.SelectSingleNode("//book[author='Corets, Eva']")
# 定位目标book下的price节点
$priceNode = $targetBookNode.SelectSingleNode("price")

# 创建length节点并赋值
$newLengthNode = $xml.CreateElement("length")
$newLengthNode.InnerText = "456"

# 将length节点插入到price节点之后
$targetBookNode.InsertAfter($newLengthNode, $priceNode)

# 保存修改后的XML,可替换为新路径避免覆盖原文件
$xml.Save($xmlFilePath)

关键说明

  • 若XML内容是字符串格式而非本地文件,将$xml.Load($xmlFilePath)替换为$xml.LoadXml('你的XML字符串内容')即可
  • PreserveWhitespace = $true配置用于保留原XML的缩进格式,避免保存后格式混乱
  • 若需要批量处理多个匹配的book节点,将SelectSingleNode替换为SelectNodes,遍历返回的节点集合执行后续插入逻辑即可

内容的提问来源于stack exchange,提问作者Keith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:15:04