kosmit
kosmit

Reputation: 671

Search for value in xml file bash script

I have xml file:

<?xml version="1.0" encoding="UTF-8"?>
<metadata>
<groupId>group</groupId>
<artifactId>project100</artifactId>
<versioning>
  <latest>1.2.1-black</latest>
  <release>1.2.1-black</release>
 <versions>
   <version>1.0.0</version>
   <version>1.0.0-black</version>
   <version>1.0.2</version>
   <version>1.0.1</version>
   <version>1.2.0</version>
   <version>1.2.1-black</version>
  </versions>
 </versionsing>
</metadata>

And also I have a variable like: $ID=1.0.2 and I want to check if this id exist in my xml file. I try something like this:

'cat ///metadata/versioning/version/text()' | xmllint --shell $content | grep -v "^/ >"

where $contenet is my xml file but this shows mi something like this:

warning: failed to load external entity "<version>1.0.0</version>

for each entity from xml file. I have no idea how to do this. I kind of noobie in bash scripting

Upvotes: 1

Views: 2654

Answers (2)

mauro
mauro

Reputation: 5950

This will tell you if ID value is present in the XML file:

$ grep -q $ID file.xml && echo exists

EDIT Excluding partial matches:

$ grep ">${ID}<" file.xml && echo exists

Upvotes: 0

Tom Fenech
Tom Fenech

Reputation: 74695

I think that $content contains the contents of your file, whereas the tool you are using expects you to pass the name of the file. It is treating each "word" of your XML (like <version>1.0.0</version>) as a path to a file and cannot find one, so is complaining.

I also notice that you're using --shell, then having to use grep to remove the prompt. You can avoid this by using --xpath directly.

I would suggest trying something like this:

echo "$content" | xmllint --xpath '//metadata/versioning/versions/version/text()' -

Or if you have the name of the file to hand, then just do this:

xmllint --xpath '//metadata/versioning/versions/version/text()' file.xml

I assume that versionsing was a typo, so I changed it to versioning in the XPath. I also added the missing part versions/ (thanks choroba).

Given that you're trying to filter to a specific version, I guess you want something like this:

$ id=1.0.0
$ xmllint --xpath "//metadata/versionsing/versions/version[text() = '$id']/text()" file.xml
1.0.0

To find out if a given version exists, you could do this:

id=1.2.3
xpath="//metadata/versionsing/versions/version[text() = '$id']"
if xmllint --xpath "$xpath" file.xml 2>/dev/null
then
    echo "version $id found"
else
    echo "version $id not found"
fi

Upvotes: 1

Related Questions