简体   繁体   中英

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

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.

Building on what @Potatoswatter said... can you create a context for the fragments? Eg 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 (eg 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.

是不是将xmlParserOptions XML_PARSE_NOERROR和/或XML_PARSE_NOWARNING传递给解析器?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM