aborruso
aborruso

Reputation: 5688

xmlstarlet: how to add element, using value of existing one

starting from

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>a feed</title>
    <link>https://afeed</link>
    <description>lorem ipsum</description>
    <item>
      <title>lorem ipsum</title>
      <description>lorem ipsum des</description>
      <pubDate>Sat, 23 Feb 2019 10:50:00 GMT</pubDate>
      <dc:date>2019-02-23T10:50:00Z</dc:date>
    </item>
    <item>
      <title>lorem ipsum sit</title>
      <description>lorem ipsum sit des</description>
      <pubDate>Sat, 23 Feb 2019 10:49:00 GMT</pubDate>
      <dc:date>2019-02-23T10:49:00Z</dc:date>
    </item>
  </channel>
</rss>

I'm able to add an element using

xmlstarlet edit --omit-decl \
    --subnode '//item' --type elem --name myelement --value myvalue \
input.xml

But how to use as value element the value of another element? Using in example

xmlstarlet edit --omit-decl \
    --subnode '//item' --type elem --name myelement --value //item/pubDate \
input.xml

I have //item/pubDate as value, but I would like to insert //item/pubDate value for every item.

Thank you

Upvotes: 2

Views: 583

Answers (1)

Cyrus
Cyrus

Reputation: 88583

Add an empty subnode and then create its content with --update and a relative path. --update has the possibility to use an xpath with --expr.

xmlstarlet edit --omit-decl \
  --subnode '//item' --type elem --name myelement \
  --update  '//item/myelement' --expr '../pubDate/text()' input.xml

See: xmlstarlet edit

Upvotes: 1

Related Questions