PowerShell – XML – Handling Nodes with and without attributes

I have to change the innertext of an XML node. But the XML node can come in various states such as:

<MachineID>1234</MachineID> 

or

<MachineID issuer="companyA">1234</MachineID> 

or

<MachineID issuer="">1234</MachineID> 

and they can be empty

<MachineID /> 

I’m trying to find a better way of handling this than:

$count = 0; try{     $XMLNode = $Value; } catch{     $count++; } try{     $XMLNode.InnerText = $Value; } catch{   $count++; } try{     $XMLNode.'#text' = $Value; } catch{     $count++; } if($count -gt 2){     echo ("Failed to set " + $XMLNode.Name + " to " + $Value); } 
Asked on July 17, 2020 in XML.
Add Comment
1 Answer(s)

It seems like node selection is the main issue here. The following works for me in your test cases.

# Assuming your xml content is in the file file.xml $x = [xml](Get-Content file.xml) $Value = 27000 $x.SelectSingleNode('//MachineID').InnerText = $Value 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.