TERACytE
TERACytE

Reputation: 7863

Writing XML strips trailing spaces

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?

Upvotes: 1

Views: 937

Answers (3)

aefxx
aefxx

Reputation: 25249

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

Upvotes: 0

TERACytE
TERACytE

Reputation: 7863

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

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798576

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

Upvotes: 1

Related Questions