Insert some XML elements with xmlstarlet

1.1k views Asked by At

I start with the followed XML file to add some datasources.

<?xml version='1.0' encoding='UTF-8'?>  
<server xmlns="urn:jboss:domain:4.2">
    <subsystem xmlns="urn:jboss:domain:datasources:4.0">
        <datasources>
            <datasource jndi-name="java:jboss/datasources/ExampleDS"
                pool-name="ExampleDS">
                <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url>
                <driver>h2</driver>
                <pool>
                    <min-pool-size>10</min-pool-size>
                    <max-pool-size>20</max-pool-size>
                    <prefill>true</prefill>
                </pool>
                <security>
                    <user-name>sa</user-name>
                    <password>sa</password>
                </security>
            </datasource>
            <drivers>
                <driver name="h2" module="com.h2database.h2">
                    <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                </driver>               
            </drivers>
        </datasources>
    </subsystem>
</server>

I'm looking for commands for this to paste into <datasource>

<datasource jndi-name="java:jboss/datasources/ExampleTestDS">
     <driver>h2</driver>
</datasource>

My current attempt for add the datasourc element is

xmlstarlet ed --subnode "/server/subsystem/datasources" \
  --type elem -n datasource -v "" \
  {INPUT_FILE}
1

There are 1 answers

0
Michael Vehrs On BEST ANSWER

The problem is that your input file uses a namespace, which you do not use in your XPath expression. Try this:

xmlstarlet ed -N x="urn:jboss:domain:datasources:4.0" \
    -s //x:datasources --type elem -n xxx \
    -s //xxx --type attr -n jndi-name -v "java:jboss/datasourcesExampleTestDS" \
    -s //xxx --type elem -n driver -v h2 \
    -r //xxx -v datasource {INPUT_FILE}

For the sake of convenience, I insert a new element called xxx and modify it before renaming it to datasource. Make sure that you use a temporary name that does not exist in your input file.