[英]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.