问题
I am using powershell to do some clean up of retro pi game lists but am stuck with the syntax for working with xml. The goal is to remove all game entries for a particular file extension type.
The list is formatted as so:
<?xml version="1.0"?>
<gameList>
<game id="" source="">
<path>./2020 Super Baseball (USA).SMC</path>
<name>2020 Super Baseball</name>
<desc />
<image>./boxart/2020 Super Baseball (USA).png</image>
<marquee>./wheel/2020 Super Baseball (USA).png</marquee>
<video>./snap/2020 Super Baseball (USA).mp4</video>
<releasedate />
<developer />
<publisher />
<genre />
</game>
<game id="" source="">
<path>./2020 Super Baseball (USA).smc</path>
<name>2020 Super Baseball</name>
<desc />
<image>./boxart/2020 Super Baseball (USA).png</image>
<marquee>./wheel/2020 Super Baseball (USA).png</marquee>
<video>./snap/2020 Super Baseball (USA).mp4</video>
<releasedate />
<developer />
<publisher />
<genre />
</game>
</gameList>
Each game has both a .smc and .SMC entry and I wish to remove the .SMC
So far I have been able iterate through the file and delete the contents of each game node that contains the .SMC extension in the path.
# Load the existing document
[xml]$xml = Get-Content "snes-gamelist.xml"
#Iterate through each game node
ForEach($Path in $xml.gamelist.game.path | Where-Object {$_ -like "*.SMC"})
{
$xml.SelectsingleNode("//path[.='"+$Path+"']") | % {
$_.ParentNode.RemoveAll() }
}
#Output
$xml.save("MOD-snes-gamelist.xml")
The issue is that the actual game node is still left behind and I am not sure how to remove it completely.
<?xml version="1.0"?>
<gameList>
<game>
</game>
<game id="" source="">
<path>./2020 Super Baseball (USA).smc</path>
<name>2020 Super Baseball</name>
<desc />
<image>./boxart/2020 Super Baseball (USA).png</image>
<marquee>./wheel/2020 Super Baseball (USA).png</marquee>
<video>./snap/2020 Super Baseball (USA).mp4</video>
<releasedate />
<developer />
<publisher />
<genre />
</game>
</gameList>
Thanks in advance.
回答1:
RemoveAll()
removes all Content from the selected node. What you want to do is to remove the entire node.
If you use
foreach($node in $xml.gameList.game | Where-Object {$_.path -clike "*.SMC")}
to get the node, you can remove it with $xml.gameList.RemoveChild($node)
.
Also you should use -clike
instead of -like
because -like
compares case-insensitive and would match both .smc and .SMC.
来源:https://stackoverflow.com/questions/44234422/powershell-searching-for-file-a-extension-in-xml-nodes-and-deleting-the-parent