xmllint: xmlns on a non-root xml element?
Asked Answered
M

2

6
xmllint --xpath "//project" test.xml

fails on

<?xml version="1.0" encoding="UTF-8"?>

<projects>
  <project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
  </project>
</projects>

but succeeds if I remove the xmlns attribute like this:

<?xml version="1.0" encoding="UTF-8"?>

<projects>
  <project>
    <modelVersion>4.0.0</modelVersion>
  </project>
</projects>

Is there some problem with this? Is xmlns legal on non-top level tags?

I'm using Java Maven:

mvn help:effective-pom

and that generates xml with the xmlns on the non-top elements like shown.

Mccombs answered 24/3, 2014 at 1:31 Comment(1)
You need to declare the namespace via the xmllint shell. See here: #8264634Medlock
S
11

The easiest workaround is to check for the local-name():

xmllint --xpath "//*[local-name()='project']" test.xml

Or, define a namespace and use it:

echo -e 'setns ns=http://maven.apache.org/POM/4.0.0\ncat //ns:project' | xmllint --shell test.xml

Also see:

Hope that helps.

Scopp answered 24/3, 2014 at 1:47 Comment(1)
Just a small note: To extract the version from a Maven pom.xml, try: xmllint --xpath '/*[local-name()="project"]/*[local-name()="version"]/text()' pom.xml <-- provides an example of multiple / chained local-name()Cr
L
1

Actually it succeeds when there is a namespace declaration. It returns an empty set, which is what the spec says it returns, so that counts as success.

Your definition of success seems to be different from the one in the spec. You don't say so, but we can guess that you are expecting the "project" elements to be returned even though they are in a different namespace from the one you are searching.

I won't go further; @alecxe has given you answer, and you will find the same question answered a thousand times if you search for "XPath default namespace". In future, though, please don't assume that we know implicitly what you expect your incorrect code to do: tell us the wanted result; and don't assume that we know what you mean by "failure": tell us what actually happens.

Leyla answered 24/3, 2014 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.