How to add a line break to each XML node?

830 Views Asked by At

How can I add a line break to each XML child bode so the output looks formatted?

The template file contains <Faults> and </Faults> tags. Now I want to insert a line break inside this node.

C++ CODE:

_di_IXMLNode nodeFault = NULL;
IXMLNode *m_pRootNode = FormMain->GetBBReportTXMLDocPtr()->DocumentElement;
...
for(; it_Events != lstEvent.end(); it_Events++){
    nodeFault = m_pRootNode->ChildNodes[EVENT_REPORT].Get(EXmlTagOrder::extoFaults)->AddChild("Fault");
    nodeFault->Attributes[WideString("Entry")] = ((*it_Events).m_sEntry).c_str();
    nodeFault->AddChild("Time")->Text = ((*it_Events).m_sTimeStamp).c_str();
    nodeFault->AddChild("Code")->Text = ((*it_Events).m_sCode).c_str();
}

But I am not getting output with line breaks or formatting.

When I open the XML file in Notepad, all nodes are on a single line:

<Faults><Fault Entry="0"><Time>0</Time><Code>20</Code></Fault><Fault Entry="1"><Time>2</Time><Code>10</Code></Faults>

The XML file looks formatted when I open it in Internet Explorer instead:

<Faults>
  <Fault Entry="0">
    <Time>0</Time>
    <Code>20</Code>
  </Fault>
  <Fault Entry="1">
    <Time>2</Time>
    <Code>10</Code>
  </Fault>
</Faults>

How can I add a line break to each node so my final output file looks formatted when I open it in Notepad++?

2

There are 2 best solutions below

1
Kerem On BEST ANSWER

You have to set some formatting options before saving to file.

In your specific case:

FormMain->GetBBReportTXMLDocPtr()->Options = 
    FormMain->GetBBReportTXMLDocPtr()->Options << doNodeAutoIndent  
1
Remy Lebeau On

Look at the FormatXMLData() function:

Formats a string of XML so that it is more readable.

Use FormatXMLData to convert a string of XML into a format that represents its structure. FormatXMLData changes the input string (XMLData) so that each element node appears on its own line, indented appropriately to reflect its nesting in the node hierarchy.