[xml] Help: Serialise sub-tree and retain namespace declarations



Hi,

I hope someone can help. I read the FAQ, studied the examples and read threads with keyword namespace to no avail.

I work with libxml2-2.7.6-21.el6_8.1.x86_64 (latest on CentOS 6 repo; it will make my life quite difficult not to work from official repositories so I can live with other bugs if at least my question below is not answered by a bug fix subsequent to this version).

I have a start document similar in concept to this

<a:root xmlns:a="http://example.com/roots" xmlns:b="http://example.com/subs" xmlns:c="http://example.com/subsubs">
    <b:sub>
        <c:subsub>Hello World</c:subsub>
    </b:sub>
</a:root>

I parse it with xmlReadFile. I then traverse the DOM to the node of sub

Using xmlNodeDump I want to output XML for sub and deeper only i.e. I want to end up with

<b:sub xmlns:b="http://example.com/subs" xmlns:c="http://example.com/subsubs">
    <c:subsub>Hellow World<c:subsub>
</b:sub>

However because the namespace declarations were in the root tag presumably, when I dump the XML, the namespace declarations are lost and I end up with

<b:sub>
    <c:subsub>Hellow World<c:subsub>
</b:sub>

which is not valid XML anymore when using a validating parser. The question is: How can I make sure the XML being output has the relevant namespace declarations added to the new top-level element i.e. to sub ?

Even if it means I need to serialize in a different manner to xmlNodeDump.

At the moment I hacked a solution by traversing the entire DOM and harvesting all namespace references and their URIs then I massage the generated text at the end by pasting the namespace declarations into the XML using string substitute functions but I have a suspicion this will bite me somewhere down the line.

Any advise will be much appreciated.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]