Search code examples
xmlstarlet

Creating valid XML with xmlstarlet


I want to use xmlstarlet to select some records of a gigantic .xml file. My problem is, that I need the output to be valid XML.

Minimal example:

using xmlstarlet sel -t -c "//record[@type='TypeA']" frage.xml

on a file frage.xml with this content:

<?xml version="1.0" encoding="UTF-8"?>
<records>
    <record type="TypeA">uqw8hY7V</record>
    <record type="TypeB">bN4mT0zL</record>
    <record type="TypeA">K6p4gJv2</record>
    <record type="TypeB">z8wQ9xV1</record>
    <record type="TypeA">a3rL7kY9</record>
    <record type="TypeB">m1W2pX4e</record>
    <record type="TypeA">y8T6r5zQ</record>
    <record type="TypeB">k9pJ2wT3</record>
    <record type="TypeA">d7V1gL5b</record>
    <record type="TypeB">t4Y6n0pM</record>
</records>

outputs:

<record type="TypeA">uqw8hY7V</record><record type="TypeA">K6p4gJv2</record><record type="TypeA">a3rL7kY9</record><record type="TypeA">y8T6r5zQ</record><record type="TypeA">d7V1gL5b</record>

while I would appreciate some NL there, my problem is, that there is no root node, which makes it uncomfortable to work with the output, because the software I want to use requires valid XML.

Is there a way to make xmlstarlet putting a root node for the output?


Solution

  • Maybe you should be removing instead of selecting? e.g.:

    xmlstarlet ed -d '//record[@type != "TypeA"]' frage.xml
    

    Output:

    <?xml version="1.0" encoding="UTF-8"?>
    <records>
      <record type="TypeA">uqw8hY7V</record>
      <record type="TypeA">K6p4gJv2</record>
      <record type="TypeA">a3rL7kY9</record>
      <record type="TypeA">y8T6r5zQ</record>
      <record type="TypeA">d7V1gL5b</record>
    </records>