Question:
I have something similar to the following in an XML document:
1 2 3 4 5 6 7 8 9 10 11 |
I am able to use Powershell to pull out certain elements within the document (such as grabbing the name or value element based on an index number). However, I don’t follow how those indices work (or whatever the indices may be called). For example, look for name[1] gives me ctrl_btn, but I would have assumed that would be name[0]. Could someone explain that?
My real problem, however, is creating a script that removes certain collections of elements within the document. For example, if I want to remove the following:
1 2 3 4 5 |
I have searched around, but most examples only remove a certain node from the XML and not a whole group as the above.
The name and value are always unique within the XML document (which, by the way, contains over 5000 different name/value combos in the <variable></variable>
element.
The list of elements I want to remove are contained within a text file that lists only the name value (e.g., the text document would list ctrl_btn and then ctrl_snpt_calctrl).
To give you better idea, here’s the whole process that the script does:
- Get the content of the XML document
- Get the value between the
<name></name>
elements for all items in the document - A search is run against a list of files to verify that the name is used within the file.
- If the name is not used, it is written a text file (e.g., not_found.txt).
- Remove the
<variable></variable>
tags and everything between them if the ` is equal to the name found in the not_found.txt.
I’m not sure if the process above helps with an explanation, but I thought I better include it.
So how do you remove these?
Answer:
Assuming you have a string array with each element being the name of a variable element you want to remove, you could do the following:
1 2 3 4 |
$names = 'ctrl_btn','ctrl_snpt_calctrl' $xml.variables.variable | ? { $names -contains $_.name } | % {$xml.variables.RemoveChild($_)} |
I am able to use Powershell to pull out certain elements within the document (such as grabbing the name or value element based on an index number). However, I don’t follow how those indices work (or whatever the indices may be called). For example, look for name[1] gives me ctrl_btn, but I would have assumed that would be name[0]. Could someone explain that?
Xml order is not guaranteed, so don’t rely on this. On my machine, for example, I get the results you expect:
1 2 3 4 |
$xml.variables.variable.name[0] = ctrl_btn $xml.variables.variable.name[1] = ctrl_snpt_calctrl |