I'm able to add a new node with a custom fixed value to my XML file in this way, with xmlstarlet:

xmlstarlet ed --subnode "/legge190/data/lotto" --type elem -n newsubnode \
-v "myvalue"

But how to add a unique identifier?

If I try to add a unique identifier using generate-id(.)

xmlstarlet ed --subnode "/legge190/data/lotto" --type elem -n newsubnode \
-v "generate-id(.)"

I do not have an id value, but the generate-id(.) string.

Thank you

  • can you post your initial xml file content? – RomanPerekhrest Sep 24 '17 at 16:05
  • Hi @RomanPerekhrest I would like a custom tag after <cig> tag gist.github.com/aborruso/…. It would be fanstastic to add ass value an ID generated via generate-id(.) – aborruso Sep 24 '17 at 17:53
  • do you want a newsubnode to look as <newsubnode>5329384ACB</newsubnode> ? – RomanPerekhrest Sep 24 '17 at 18:21
  • @RomanPerekhrest, yes I want something like <newsubnode>5329384ACB</newsubnode>, not writing -v "5329384ACB", but using an XPATH function like -v "generate-id(.)". Thank you – aborruso Sep 24 '17 at 20:11
  • unfortunately, generate-id function won't work in xmlstarlet edit ed mode. I can suggest a solution for copying id from node <cig> to node <newsubnode> – RomanPerekhrest Sep 24 '17 at 20:46

I have solved with a xsl file like this one:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="cig"> <lottoID><xsl:value-of select="generate-id(.)"/></lottoID> <!-- a linefeed --> <xsl:text>&#xa;</xsl:text> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

The id is generated by generate-id XPATH function.

In this way I copy all nodes and insert a unique identifier in the <lottoID> element just before the <cig> element (that is a element of my input XML file).

The command with xmlstarlet is:

xmlstarlet tr stile.xsl input.xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.