views:

101

answers:

2

Hi guys,

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 namespace error warning.

Thank you very much.

A: 

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

Bart van Ingen Schenau
I don't want to remove all errors - just that specific one.Also, I'm using xmlParseMemory() which doesn't take a xmlParserOption parameter (why the heck are there xmlParseMemory() and xmlReadMemory() which both seem to be doing pretty much the same thing?)
Artem Russakovskii
+3  A: 

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.

LarsH
I think xmlParseInNodeContext() is key. It is designed for parsing document fragments, which is what you have.
Mark Thomas