xmllint: xmlns on a non-root xml element?

拥有回忆 提交于 2020-01-03 10:04:21

问题


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.


回答1:


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:

  • xmllint failing to properly query with xpath
  • XPath select node with namespace
  • xmllint and namespace

Hope that helps.




回答2:


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.



来源:https://stackoverflow.com/questions/22599627/xmllint-xmlns-on-a-non-root-xml-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!