beevik / etree

parse and generate XML easily in go
BSD 2-Clause "Simplified" License
1.47k stars 175 forks source link

how to pretty print when writing back #116

Closed liesauer closed 1 year ago

liesauer commented 1 year ago
<root>
  <first />
</root>

if i insert a second element, the xml will become like this

<root>
  <first />
  <second /></root>
beevik commented 1 year ago

Closed, as the issue does not describe the problem that needs to be solved.

liesauer commented 1 year ago

this is my xml

<root>
  <first />
</root>

and i am trying to insert a second element into root

doc := etree.NewDocument()

doc.ReadFromFile(xmlFile)

root := doc.FindElement("./root")

root.CreateElement("second")

doc.WriteSettings.UseCRLF = true

bytes, _ := doc.WriteToBytes()

expected result

<root>
  <first />
  <second />
</root>

actual result

<root>
  <first />
  <second /></root>

should be clear enough, thanks for the responsing.

beevik commented 1 year ago

The etree document has no way of knowing how a document has been formatted with respect to whitespace, so it cannot infer that it needs to insert a newline after creating a child element. However, you can call Indent before writing the document to force whatever indenting you like. For example:

doc.Indent(2)
bytes, _ := doc.WriteToBytes()
liesauer commented 1 year ago

thanks.