简体   繁体   中英

Powershell script to remove an XML sub-elements

I'm having a problem trying to remove some sub-elements from an XML file.

<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>

I want to remove the whole line " Parameter name="l" value="EAI" "

Any ideas? I was trying this but it is returning nothing to me.

# 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($_)

You were close - you just needed to add Parameter to the end of $xml.Smart.Settings.Section - see below for how to remove all <Parameter "name="l" value="EAI" /> nodes from the document:

$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");

this solution does not make use of any fancy XML but reads the file, filters the string and outputs the result to a new file. maybe this works for you?

$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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM