Extract value of element in XML with xmlstarlet

My situation is very specific, and I am a beginner with xmlstarlet.

I have an XML file like the one below, which contains hundreds of entries.

<netbooks>
  <file id="2">
    <date>2008-06-04 16:40</date>
    <author>Daniel</author>
    <name bytes="422904" hash="383a39b183">New name of - Just an example.pdf</nome>
    <name bytes="383135" hash="5a43dc3524">Just an example.pdf</nome>
  </file>
</netbooks>

Where root = netbooks tag.

QUESTIONS

  1. I have the file hash 5a43dc3524, i want to take the value of date, that is 2008-06-04 16:40. What’s the easiest way to do this?
  2. Also, how to get the attribute id (that is 2) from file element? Again, I have the hash, just it.
Asked By: Daniel

||

I have the file hash 5a43dc3524, i want to take the value of date, that is 2008-06-04 16:40. What’s the easiest way to do this?

We can get the date using the xpath expression //file[name/@hash="5a43dc3524"]/date/text(). Assuming that the file data.xml contains the sample data from your question, if we run:

xmlstarlet sel -t -v '//file[name/@hash="5a43dc3524"]/date/text()' data.xml

We get the output:

2008-06-04 16:40

The expression //file[name/@hash="5a43dc3524"]/date/text() means "find all the <file> elements that contain a <name> element in which the value of the hash attribute is 5a43dc3524. For each <file> element, get the value of the contained <date> element and return its text value.

Also, how to get the attribute id (that is 2) from file element? Again, I have the hash, just it.

We can do something very similar:

xmlstarlet sel -t -v '//file[name/@hash="5a43dc3524"]/@id' data.xml
Answered By: larsks
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.