4

I'm trying to generate an xml using boost. Going fine so far, but the xml that gets generated needs to have a namespace.

so instead of <name>"Harry"</name> it would say <ns1:name>"Harry"</ns1:name>

Is there any way to add a namespace to the XML with boost without manually adding the "ns1" to every line?

sehe
  • 374,641
  • 47
  • 450
  • 633
Aelion
  • 379
  • 1
  • 5
  • 16

3 Answers3

2

Is there any way to add a namespace to the XML with boost without manually adding the "ns1" to every line?

Assuming you use rapidxml, no you cannot. You could however extend rapidxml to support this or obtain a copy of a parser that does support this (see sehe's answer).

There is even a fork of rapidxml which already supports this (you would just have to replace it). Or you could just add the namespace by manually adding the string.

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
  • 1
    Good information this. I just found PugiXML doesn't even support XML namespaces (properly). :| Boost Property Tree might be able to help still ... – sehe Jan 28 '16 at 12:28
1

Boost doesn't have an XML library, so you can't.

I'd suggest picking your XML library from here: What XML parser should I use in C++?

My personal favorite is PugiXML Update Pugi doesn't support namespaces (eek):

Namespace nodes are not supported (affects namespace:: axis).

However, to answer this part of the question:

Is there any way to add a namespace to the XML with boost without manually adding the "ns1" to every line?

You could logically achieve with the (dubious) feature Default Namespaces:

<?xml version="1.0"?>
library xmlns="http://eric.van-der-vlist.com/ns/library">
...
</library>

Everything will be seen as logically from that namespace, even without a prefix.

Now, boost doesn't document how to do this, but you can get to it:

Add xml-stylesheet processing instructions to boost property_tree

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 1
    Added an out-of-the-box workaround for Boost Property Tree – sehe Jan 28 '16 at 12:27
  • 1
    I like this option but feel like another parser might be the better option afterall :) – Floris Velleman Jan 28 '16 at 12:30
  • 1
    @FlorisVelleman Sure thing. It's just something to _realize_ (the way the OP phrased the question makes me think he doesn't know this about XML namespaces) – sehe Jan 28 '16 at 12:47
0

So, I managed to get the result I wanted. Here's what I did:

My outer most element was called 'Document':

ptree& documentnode = pt.add("namespace1:Document", "");

then added tags to the element for each namespace:

pt.add("Document.<xmlattr>.xmlns:namespace1", "value");

Then in front of each element I'll have to add "namespace1":

documentnode.add("namespace1:name", "Harry");

output:

<namespace1:Document xmlns:namespace1=value>
    <namespace1:name>Harry</namespace1:name>
</namespace1:Document>

Probably not the best solution, but it suits my needs.

Aelion
  • 379
  • 1
  • 5
  • 16