3

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.
0

1 Answer 1

5

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
5
  • Thanks, this is exactly what I was looking for. Xmlstarlet --help is pretty bad. Do you know any site with good documentation or friendly tutorial to point me to?
    – Daniel
    Jul 4 at 14:05
  • 1
    Search for "introduction to xpath" and you will find many, many articles with information about writing xpath expressions. I don't have any specific recommendations that I think are better than others.
    – larsks
    Jul 4 at 14:13
  • 1
    There are quite a lot of xmlstarlet Q&A here too Jul 4 at 14:56
  • 1
    @roaima yes, i have saved many of these answers too.
    – Daniel
    Jul 4 at 16:07
  • @daniel: xmlstarlet select --help?
    – Cyrus
    Jul 4 at 21:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .