[英]Powershell script to remove an XML sub-elements
我在尝试从 XML 文件中删除一些子元素时遇到问题。
<Smart>
<Settings>
<Section name="x">
<Parameter name="a" value="true" />
<Parameter name="b" value="0" />
<Parameter name="c" value="13873" />
<Parameter name="d" value="true" />
<Parameter name="e" value="EAI" />
</Section>
<Section name="z">
<Parameter name="h" value="true" />
<Parameter name="i" value="0" />
<Parameter name="j" value="13873" />
<Parameter name="k" value="true" />
<Parameter name="l" value="EAI" />
</Section>
</Settings>
</Smart>
我想删除整行“ Parameter name="l" value="EAI" "
有任何想法吗? 我正在尝试这个,但它没有给我任何回报。
# Read the XML file
Write-Host "OPENING XML FILE";
LogWrite "OPENING XML FILE";
$path = "\\$computer\$FileName"
[xml] $xml = Get-Content $path
# Deleting node
$npSectionName = "x"
$xml.Smart.Settings.Section | Where-Object { $_.name -eq $npSectionName } | % {
#Remove node
$xml.Settings.RemoveChild($_)
您很接近 - 您只需将Parameter
添加到$xml.Smart.Settings.Section
的末尾 - 请参阅下文,了解如何从文档中删除所有<Parameter "name="l" value="EAI" />
节点:
$xml = @"
<Smart>
<Settings>
<Section name="x">
<Parameter name="a" value="true" />
<Parameter name="b" value="0" />
<Parameter name="c" value="13873" />
<Parameter name="d" value="true" />
<Parameter name="e" value="EAI" />
</Section>
<Section name="z">
<Parameter name="h" value="true" />
<Parameter name="i" value="0" />
<Parameter name="j" value="13873" />
<Parameter name="k" value="true" />
<Parameter name="l" value="EAI" />
</Section>
</Settings>
</Smart>
"@;
$data = [xml] $xml;
# find the nodes we want to remove
$parameters = $data.Smart.Settings.Section.Parameter `
| where-object { ($_.name -eq "l") -and ($_.value -eq "EAI") }
# remove them
foreach( $parameter in $parameters )
{
$null = $parameter.ParentNode.RemoveChild($parameter);
}
$data.Save("c:\temp\smart.xml");
该解决方案不使用任何花哨的 XML 而是读取文件,过滤字符串并将结果输出到新文件。 也许这对你有用?
$filePath = 'c:\tmp\smartxml.xml'
$fileContent = Get-Content -Path $filepath
$filterString = 'Parameter name="l" value="EAI"'
$newFilePath = 'c:\tmp\smartnew.xml'
foreach($line in $filecontent) {
if($line -notmatch $filterString) {
Out-File -FilePath $newFilePath -Append -InputObject $line
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.