Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use C++ to create XML file

Status
Not open for further replies.

Kangwei

Programmer
Nov 24, 2002
3
SG
Can I use C++ to create XML file? If Yes, please give the codes.
 
You sure can. All you have to do is create strings in C++. You can do this a multitude of ways. In MFC, for example, you could use the CString class, in STL, the string class. You could also use the _bstr_t for BSTR. At any rate, after you create the string, then write the string out to a file. The important things to remember is that XML has to be &quot;Well-Formed&quot;. Unlike HTML, each opening tag must have a matching closing tag (with the exceptions of self-closing tags <tagName/>) and tags must not cross other tag boundaries. By crossing tag boundaries I mean, you can not open a tag, open a second tag and close the first tag with out first closing the second tag. For example, the following is illegal in XML:

<Tree>
<leaf>
</Tree>
</leaf>

The correct way would be:
<Tree>
<leaf>
</leaf>
</Tree>

The other important thing about XML to remember is that you can only have ONE root tag. Doing the following is illegal:
<Tree>
<leaf>
</leaf>
</Tree>
<Tree>
<leaf>
</leaf>
</Tree>

You must do this:
<Forest>
<Tree>
<leaf>
</leaf>
</Tree>
<Tree>
<leaf>
</leaf>
</Tree>
</Forest>

Adding the forest tag provides a single root tag.

Enough about XML... on to your problem. You can create a string instance like:
string s = &quot;&quot;;
and concatenate all the XML in to it. Like:
s += &quot;<Root><someothertag/></Root>&quot;;
and then write it to a text file.

If your xml becomes so large that one string cannot hold it all, then create mulitple strings and write each string, in succession to the file.

Hope this helps.

Joe.
 
A better way would be to either use the Xerces code freely available on the Web or use the Microsoft (MSXML)COM component (also downloadable).
 
I agree with Temps, the last thing you want to do is write a bunch of string concatination code.

-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top