Search code examples
xmlshxmlstarlet

Add XML node based on two of parents child values in the shell


How can I change this:

...
<dependencies>
    ...
    <dependency>
        <groupId>xyz</groupId>
        <artifactId>abc</artifactId>
    </dependency>
    ...
</dependencies>
...

to that:

...
<dependencies>
    ...
    <dependency>
        <groupId>xyz</groupId>
        <artifactId>abc</artifactId>
        <scope>system</scope>
        <systemPath>/.../src/main/.../some.jar</systemPath>
    </dependency>
    ...
</dependencies>
...

based on the value of "/dependencies/dependency/groupId" AND "/dependencies/dependency/artifactId"

in bash (by xmlstarlet,...)?

Update

Obviously this seems to be not clear enough. So: The code has to find the dependency with groupId==xyz and artifactId==abc and then (and only then) add the two now nodes to the parent of the groupId and artifactId node.


Solution

  • With the help of @Jack Fleeting and the post from @uk4sx (XMLStarlet does not select anything) - the namespace had to be set - I finally got it running like this (it it run from within a Dockerfile):

    RUN xmlstarlet ed -L -N my=http://maven.apache.org/POM/4.0.0 \
        --subnode "//my:dependencies/my:dependency[my:artifactId[./text()='abc']][my:groupId[./text()='xyz']]" \
          --type elem -n scope      -v "system" \
        --subnode "//my:dependencies/my:dependency[my:artifactId[./text()='abc']][my:groupId[./text()='xyz']]" \
          --type elem -n systemPath -v "\.../src/main/.../some.jar" \
        ./pom.xml