Can I insert a sub element with one call to XMLStarlet and still have correct formatting?

1.1k Views Asked by At

I was using an awesome tip from cellux to add a new element (with attributes and sub elements) under an existing element in this question and ran into a formatting challenge.

Starting with a file example.xml:

<processes>
  <process id="test"/>
</processes>

If I use cellux's method of doing multiple with a single call to xml with multiple actions...

xml ed -L \
  -s "/processes" -t elem -n processTMP -v "" \
  -i "/processes/processTMP" -t attr -n id -v "test2" \
  -s "/processes/processTMP" -t elem -n subproc -v "s2" \
  -r "/processes/processTMP" -v "process" \
  example.xml

the resulting file contains one new line of XML.

<processes>
  <process id="test"/>
  <process id="test2"><subproc>s2</subproc></process>
</processes>

If I make multiple calls to xml with each in a separate call...

xml ed -L -s "/processes" -t elem -n processTMP -v "" example.xml
xml ed -L -i "/processes/processTMP" -t attr -n id -v "test2" example.xml
xml ed -L -s "/processes/processTMP" -t elem -n subproc -v "s2" example.xml
xml ed -L -r "/processes/processTMP" -v "process" example.xml

I get well formatted (indented) XML.

<processes>
  <process id="test"/>
  <process id="test2">
    <subproc>s2</subproc>
  </process>
</processes>

The two files are syntactically identical, but I'd like to keep the XML as clean as possible.

Does anyone know of a clean way to make a single call to xml and still get the formatting? I know I could run it through "xml fo" at the end, but there has to be a better way.

0

There are 0 best solutions below