views:

126

answers:

3

I am trying to write an XML file using MSXML4. It works fine except when I have a data element with a trailing space which must be preserved.

Given the following code to insert a new element:

const _bstr_t k_Parent      (ToBSTR("ParentNode"));
const _bstr_t k_Child       (ToBSTR("ChildNode"));
const _bstr_t k_Data        (ToBSTR("DataWithTrailingSpace "));
const _bstr_t k_Namespace   (ToBSTR("TheNameSpace"));

MSXML2::IXMLDOMDocument2Ptr m_pXmlDoc;

m_pXmlDoc->async = VARIANT_FALSE;
m_pXmlDoc->validateOnParse = VARIANT_FALSE;
m_pXmlDoc->resolveExternals = VARIANT_FALSE;
m_pXmlDoc->preserveWhiteSpace = VARIANT_TRUE;

MSXML2::IXMLDOMNodePtr pElement = m_pXmlDoc->createNode(NODE_ELEMENT, k_Child, k_Namespace);
MSXML2::IXMLDOMNodePtr pParent = m_pXmlDoc->selectSingleNode(k_Parent);

pElement->put_text (k_Data);

MSXML2::IXMLDOMNodePtr pNewChild = pParent->appendChild(pElement);

If I check "pNewChild->text", the text still contains the trailing space. When I try writing it to a file:

std::string xml (static_cast<std::string>(m_pXmlDoc->xml));

std::ofstream file("output.xml");

file << xml << std::endl;

file.flush();
file.close();

The output is:

<ParentNode>
    <ChildNode>DataWithTrailingSpace</ChildNode>
</ParentNode>

Instead of (note the extra space behind "DataWithTrailingSpace"):

<ParentNode>
    <ChildNode>DataWithTrailingSpace </ChildNode>
</ParentNode>

I cannot figure out at what point the trailing space is getting stripped.

Can someone please provide some insights in to where this may be occurring and how I can correct it?

A: 

You should replace the whitespace(s) with &#xa0;. That way your whitespaces should persist.

EDIT
Appearantly it didn't solve your problem. Then maybe you want to have a look at these sites: http://msdn.microsoft.com/en-us/library/ms757008(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms757885(VS.85).aspx

aefxx
I cannot get that to work. I end up with: <ChildNode>DataWithTrailingSpace  </ChildNode>The space is there, between the data and " ".
TERACytE
+1  A: 

If you need to preserve whitespace then you should be using a CDATA section via createCDATASection() or the like.

Ignacio Vazquez-Abrams
While this preserves the space it also injects "<![CDATA[" in to the XML, which I cannot support. The system that receives it rejects it because the 'data' is in an invalid format.The output must be "<ChildNode>DataWithTrailingSpace </ChildNode>".
TERACytE
Then your receving system __does not support XML__. In XML, "<ChildNode>DataWithTrailingSpace </ChildNode>" is _exactly_ the same as "<ChildNode><![CDATA[DataWithTrailingSpace ]]></ChildNode>"
MSalters
A: 

Mystery solved. Don't preview your XML in Internet Explorer. It hides trailing spaces. Use notepad instead.

TERACytE