Rachel Ambler
Rachel Ambler

Reputation: 1604

Modify XML file to clear a value & set it to a self closed element in Powershell

Consider the following XML:

<A type="Something">
  <B version="1">
    <C version="1">
      <D version="1">
        <This>True</This>
        <That>True</That>
      </D>
    </C>
  </B>
</A>

This is the Powershell script I've got so far to manipulate it:

[xml] $someXml = [xml] (Get-Content $myFile)
$someXml.A.B.C.D.This = "False"
$someXml.A.B.C.D.That = ""
$someXml.Save($myFile)

If I run that I get

<A type="Something">
  <B version="1">
    <C version="1">
      <D version="1">
        <This>False</This>
        <That></That>
      </D>
    </C>
  </B>
</A>

Whereas what I'm really after is

<A type="Something">
  <B version="1">
    <C version="1">
      <D version="1">
        <This>False</This>
        <That/>
      </D>
    </C>
  </B>
</A>

So, the question is, how do I set That to force the element to be self-closing?

Yes, I know that they're both syntacticly identical, however I have my own reasons why I need it to be a self-closing tag.

Upvotes: 2

Views: 930

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

After clearing the inner text value, set the value of the IsEmpty property on the node to $true:

$someXml.A.B.C.D.GetElementsByTagName('That')[0].IsEmpty = $true

This will cause a collapsed tag when the document gets written to file/output:

enter image description here

Upvotes: 5

Related Questions