user2731629
user2731629

Reputation:

Save adds return linebreaks to XML when elements are blank

I'm loading a XML Document that has some tags that have no innertext.

If I populate the innertext with some data then it works as needed (you get opening tag, innertext and closing tag all on one line) like the following...

<element>value</element>

The problem arises with tags with no values. These SHOULD be displayed in the same way as above with the exception of no value of course, like the following:

<element></element>

However, when the innertext has an empty string it adds a carriage return & line feed which is not what is expected! It ends up looking like the following:

<element>
</element>

My code:

$input_dir  = "F:\uma\zz"
$output_dir = "F:\uma\zz"
[xml]$xdoc  = Get-Content "$input_dir\Subnet_Network_41.xml"
$inprange   = 5
foreach ($i in $inprange) {
    $xdoc.Subnet.Id   = "Network_$i"
    $xdoc.Subnet.Name = "Network_$i"
    $xdoc.Save("$output_dir\Subnet_Network_$i.xml")
}

Upvotes: 5

Views: 1680

Answers (1)

user2731629
user2731629

Reputation:

I have fixed the issue myself. I have used Select-xml to read the xml file and it worked. It didnt add the return linebreaks while saving the xml document. below is the working code.

$input_dir  = "F:\uma\zz"
$output_dir = "F:\uma\zz"
$xdoc = ( Select-Xml -Path $input_dir\Subnet_Network_41.xml -XPath / ).Node
$inprange   = 5
foreach ($i in $inprange) {
    $xdoc.Subnet.Id   = "Network_$i"
    $xdoc.Subnet.Name = "Network_$i"
    $xdoc.Save("$output_dir\Subnet_Network_$i.xml")
}

To know more about Select-xml refer the below blog: https://blog.stangroome.com/2014/02/10/powershell-select-xml-versus-get-content/

Upvotes: 3

Related Questions