libxml2 error with namespaces and xpath

假如想象 提交于 2019-11-29 03:49:34

Turns out, as I found out from here, it is not really a failure of libXml, it's a problem because libXml correctly follows the XML/XPATH specifications.

The solutions proposed by R Bourdeau are correct, however, if you have control of the xml document you are parsing.

The context for the XPATH query is independent of the namespace qualifiers in the xml document. The default namespace forces all child tags into a namespace; they don't require qualification in the document but must be qualified in the xpath query. Fortunately, you registered the namespace as new with libXml, so cateof's solution should work.

xmlXPathRegisterNs(context,  BAD_CAST "new", BAD_CAST "http://www.example.com/new"

xmlChar *xpath = (xmlChar*) "/new:book/new:section1";

I'm inlining the xml here for visibility:

<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.example.com/new">
    <section1>Sec_1</section1>
    <section2>Sec_2</section2>
</book>

This is an annoying failure of the libXml library. As noted by cateof, the problem is the default namespace declaration:

xmlns="http://www.example.com/new"

Two choices:
(1) get rid of that declaration in your book tag or (2) give it a name, and use that name in your tags.

e.g.

xmlns:new="http://www.example.com/new"

Then your tags all look like:

new:book new:section1

and so on.

it is an issue with the default namespace. To match a path you need /new:tag/new:tag and so on

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