$ vim test.xml
<?xml version="1.0" encoding="UTF-8" ?>
<config>
</config>
$ xmlstarlet ed -i "/config" -t elem -n "sub" -v "" test.xml
<?xml version="1.0" encoding="UTF-8"?>
<sub></sub>
<config>
</config>
But I wanted sub to be a child of config. How should I change the xpath parameter of -i?
BONUS: Is it possible to insert the child directly with an attribute and even have it set to a value? Something like:
$ xmlstarlet ed -i "/config" -t elem -n "sub" -v "" -a attr -n "class" -v "com.foo" test.xml
From version 1.4.0 of XMLStarlet (dated 2012-08-26), you can use
$prev
(or$xstar:prev
) as the argument to-i
,-a
, and-s
to refer to the last nodeset inserted. See the examples in the XMLStarlet source code in the filesdoc/xmlstarlet.txt
,examples/ed-backref1
,examples/ed-backref2
, andexamples/ed-backref-delete
. You no longer need to use the trick of inserting the element with a temporary element name and then renaming it at the end. The exampleexamples/ed-backref2
is particularly helpful in showing how to define a variable to use to refer to a (the) previously-created note so that you don't need to do tricks such as$prev/..
to "navigate" out of a node.I had a similar problem: I had a Tomcat configuration file (server.xml), and had to insert a
<Resource>
tag with pre-defined attributes into the<GlobalNamingResources>
section.Here is how it looked before:
Here is what I wanted to achieve:
Here is how I did it (snippet from a shell script):
The trick is to temporarily give a unique name to the new element, so that it can be found later with an XPATH expression. After all attributes have been added, the name is changed back to Resource (with -r).
The meaning of the other xmlstarlet options:
The example did not work until I wrapped
<GlobalNamingResources>
into a<Server>
element.Use
-s
(or--subnode
) instead of-i
. Regarding the bonus, you can't insert an element with an attribute directly but since every edit operation is performed in sequence, to insert an element and then add an attribute:I tried the trick from cellux above.,It worked great! Thanks!! But, the formatting was not persisted, just to try, I got rid of options -P and -S, and the formatting issues were gone! I am using CentOS. May be this can help someone.