Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opening/saving xml while preserving newline between node's attributes

This is what I have so far:

$XML = New-Object System.Xml.XmlDocument
$XML.PreserveWhitespace = $true
$XML.Load($path)
#change some node attributes
$XML.Save($path)

If I take open an XML file, and take a snippet like this:

<Node 
Name="tyjytj" 
Number="rthjr" 
Source="rjyrtjrjrtj" 
BinaryDrive="teheherhehtr" />

It will save it like this:

<Node Name="tyjytj" Number="rthjr" Source="rjyrtjrjrtj" BinaryDrive="teheherhehtr" />

But I want to be able to change (for example) the Name of the Node, while keeping newlines between each attribute. I want the format to remain exactly how it was before I open/saved it.

like image 354
jsirr13 Avatar asked Nov 26 '22 16:11

jsirr13


1 Answers

Please have a look at this answer to a question very similar to yours:

While there doesn't seem to be a way of preserving xml attribute formatting, you can define it yourself on the xml document by using the power of the XmlWriterSettings and XmlWriter classes.

You can specify it to have newlines between attributes like so:

$xwSettings = new-object System.Xml.XmlWriterSettings
$xwSettings.NewLineOnAttributes = $true

You then save the document using an XmlWriter together with these settings:

$xmlWriter = [Xml.XmlWriter]::Create("c:\temp\newlines.xml", $xwSettings)
$doc.Save($xmlWriter)

(Code is all from original answer. Kudos to vonPryz)

like image 190
Paul Siersma Avatar answered Nov 29 '22 06:11

Paul Siersma