Removing nodes from XML file with PowerShell

goowpea 1 Reputation point
2022-12-29T12:23:03.06+00:00

Hi all,

I stumbled onto a problem and I don't know what's causing it. I have a pretty lengthy XML file with a structure as on the picture:
274749-image-2022-12-29-130726296.png

I want to remove "users" part from it. I wrote a short script in PowerShell to remove the node for me and then save the changed file with a new name.

I tried it on a small, test XML file (about 200 lines) and it works perfectly fine. When I try to run the script on the destination file it gives me no errors, no prompts nothing. It saves the file with a new name, but it's unchanged.

My script:

$xml = [xml](Get-Content C:\PSscripts\sample.xml)
$xml.SelectNodes("//users")
$nodes = $xml.SelectNodes("//users")
foreach($node in $nodes){$node.ParentNode.RemoveChild($node)}
$xml.Save('C:\PSscripts\sample2.xml')
echo = $xml

I tried echoing it see the tree structure, but it looks like the XML file is empty:

**PS C:\Users\goowpea> [xml]$xml = (Get-Content C:\PSscripts\sample.xml)
$xml.SelectNodes("//users")

echo = $xml

xml im-solution
version="1.0" encoding="UTF-8" standalone="yes" im-solution**

I tried "SelectSingleNode" as well:

$xml = [xml](Get-Content C:\PSscripts\sample.xml)
$node = $xml.SelectSingleNode("//users")
$node.ParentNode.RemoveChild($node) | Out-Null
$xml.Save('C:\PSscripts\sample2.xml')

l and it gives me a different error:

You cannot call a method on a null-valued expression.
At line:3 char:1

  • $node.ParentNode.RemoveChild($node) | Out-Null
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  • CategoryInfo : InvalidOperation: (:) [], RuntimeException
  • FullyQualifiedErrorId : InvokeMethodOnNull

I guess it's because it's not getting the variable since it can't read into the XML file tree.

The file is pretty long as it has over 200 000 lines. Is there any limit for PowerShell when it comes to lines?
Do you know what the problem might be here?

Windows for business Windows Server User experience PowerShell
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2023-01-04T21:28:27.847+00:00

    Well, I'm going to guess that there are namespaces in the file referenced by xmlns=http://www.ptc.com/integrity-solution. What they are, I don't know. If there are namespaces you'll have to add the ones you want and then add the namespace table of the XML document. After that, you'll have to add the namespace table as a 2nd parameter to the SelectNodes.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.