0

Given the following xml file:

<?xml version="1.0"?>
<tomcat-users>
    <user password="PASSWORD-1"
          roles="manager-script"
          username="manager-script"/>
 <role rolename="manager-gui"/>
<user username="tomcat" password="SECRET" roles="manager-gui"/>
</tomcat-users>

I am trying to get the following output string, using the xmllint command: PASSWORD-1.

I googled and read quite a lot, and being new to XML parsing, I honestly can't figure it out.

Any idea?

befo88
  • 43
  • 1
  • 5
  • XPath would be: `/tomcat-users/user/@password`. I'm unfamiliar with `xmllint` though. If you only want the first password: `(/tomcat-users/user/@password)[1]`. – JohnLBevan Jun 19 '17 at 20:36

1 Answers1

0

The XPath required is: (/tomcat-users/user/@password)[1] (i.e. returns the first password attribute of a user in the file.

If you want the password of the first user in the file (subtly different, as there's no guarantee that the first user has a password defined), use /tomcat-users/user[1]/@password.

If you want all users' passwords, use /tomcat-users/user/@password.

I was unfamiliar with xmllint, so referred to: How to execute XPath one-liners from shell? The syntax is: xmllint --xpath '(/tomcat-users/user/@password)[1]' inputFile.xml

When building an XPath statement, think of it as typing the directory to a file on your file system; you have pieces nested under other pieces, so name the root, then put a slash and name its child, repeating the process until you get to the item you're after. For attributes, the name should be prefixed with an @ to show it's an attribute. Stuff in square brackets is a way of filtering when you may have a "path" which leads to multiple results. Just putting a number in the square brackets gives you the element at that position (first element is #1; not #0 as in most languages). There are more advanced things you can do with these filters; but that's going beyond the scope of your question.

JohnLBevan
  • 22,735
  • 13
  • 96
  • 178