简体   繁体   中英

PowerShell: Locate parent node and edit children

I have a given XML file with 0 to n nodes called <Launch.Addon>. I would like to locate the '<Launch.Addon>' node with the child node 'Name' that contains the value 'VRS_TacPack'. If found i need to edit the child nodes 'Disabled' and 'ManualLoad' and then write the changed XML file back.

Structure of the given XML file:

<?xml version="1.0" encoding="Windows-1252"?>
<SimBase.Document Type="Launch" version="1,0">
  ...
  <Launch.Addon>
    <Name>BlaBlaBla</Name>
    ...
  </Launch.Addon>
  <Launch.Addon>
    <Name>VRS_TacPack</Name>
    <Disabled>True</Disabled>
    <ManualLoad>False</ManualLoad>
    <Path>Modules\VRS_TacPack\VRS_TacPack.dll</Path>
  </Launch.Addon>
  <Launch.Addon>
    <Name>BluBluBlu</Name>
    ...
  </Launch.Addon>
  ...
</SimBase.Document>

Reading and writing the XML file is no problem but since I do not know how to naviage inside an XML structure all my atempts to figure this out using examples failed miserably.

My current state of the script

# Set up new XML object and read DLL.XML file content
$xmlDll  = New-Object System.XML.XMLDocument
$xmlDll.Load($tacPackFileSpec)
    
# Get the <Launch.Addon> node with child node <Name> contains 'VRS_TacPack'
???
    
# Output modified DLL.XML file
$xmlDll.Save($tacPackFileSpec)

Thanks a lot for any help or hints Hannes

Here's two options for you:

[xml]$xml = @"
<?xml version="1.0" encoding="Windows-1252"?>
<SimBase.Document Type="Launch" version="1,0">
  <Launch.Addon>
    <Name>BlaBlaBla</Name>
  </Launch.Addon>
  <Launch.Addon>
    <Name>VRS_TacPack</Name>
    <Disabled>True</Disabled>
    <ManualLoad>False</ManualLoad>
    <Path>Modules\VRS_TacPack\VRS_TacPack.dll</Path>
  </Launch.Addon>
  <Launch.Addon>
    <Name>BluBluBlu</Name>
  </Launch.Addon>
</SimBase.Document>
"@

Using XPATH (Case-Sensitive)

$xml.SelectNodes("//Launch.Addon/Name[contains(text(), 'VRS_TacPack')]") | ForEach-Object {
    $_.ParentNode.Disabled   = 'False'
    $_.ParentNode.ManualLoad = 'True'
}

$xml.Save("D:\Test\blah.xml")

Using 'dotted' properties (Case-Insensitive)

# need to quote the element names because of the '.'
$xml.'SimBase.Document'.'Launch.Addon' | Where-Object { $_.Name -eq 'VRS_TacPack' } | ForEach-Object {
    $_.Disabled   = 'False'
    $_.ManualLoad = 'True'
}
$xml.Save("D:\Test\blah.xml")

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