开发者

Filtering out namespace errors when parsing partial XML via libxml2 in C++

开发者 https://www.devze.com 2023-01-06 18:21 出处:网络
I have the need to parse partial XML fragments (which are presented as std::string), such as this one:

I have the need to parse partial XML fragments (which are presented as std::string), such as this one:

<FOO:node>val</FOO:node>

as xmlDoc objects in libxml2, and because these are fragments, I keep getting the namespace error : Namespace prefix FOO on node is not defined errors spit out into STDERR.

What I am looking for is for either a way to filter just these namespace warnings out or parse the XML fragment straight into a xmlNode object.

I think some sort of hacking around with initGenericErrorDefaultFunc() may be in order to go the first way, but the documentation for libxml2 is absolutely atrocious.

I would frankly prefer to go with the 2nd approach because it would require no error hacking and the node would be already aware of the namespace, but I don't think it's possible because the node has to have a root and XML fragments are not guaranteed to have only one root.

I just need some guidance here of how to rid myself of the namesp开发者_如何学编程ace error warning.

Thank you very much.


Building on what @Potatoswatter said... can you create a context for the fragments? E.g. concatenate

<dummyRoot xmlns:FOO="dummy-URI">

in front of your fragment, and

</dummyRoot>

afterward, then pass the concatenated string to xmlParseMemory().

Alternatively, why don't you use xmlParseInNodeContext(), which lets you pass in a node to use as context (including namespaces), and the content can be any Well Balanced Chunk (e.g. multiple elements with no single root element).

Either method requires that you know, or can scan to find out, the set of all possible namespace prefixes that the fragment may use.


Is it not an option to pass the xmlParserOptions XML_PARSE_NOERROR and/or XML_PARSE_NOWARNING to the parser?

0

精彩评论

暂无评论...
验证码 换一张
取 消