Setting the XML Declaration With CMarkup

The XML Declaration is the version tag that appears at the beginning of document. It is optional when it is the default version 1.0 and ASCII (which is a subset of UTF-8) or any Unicode encoding.

<?xml version="1.0" encoding="UTF-8"?>

When you instantiate your CMarkup object, pass the XML declaration including a CRLF if you want.

CString strDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
CMarkup xml( strDecl + "\r\n" );

Or pass it to your SetDoc call.

xml.SetDoc( strDecl + "\r\n" );

If the document already exists and you want to add an XML declaration to the beginning, you can concatenate it to the document string and re-parse.

xml.SetDoc( strDecl + "\r\n" + xml.GetDoc() );

The most efficient way to add the XML declaration to the beginning of the existing document is with InsertNode and specifying only the data that goes inside the processing instruction (by the way, it adds the CRLF automatically, see Node Methods in CMarkup).

CString strDeclData = "xml version=\"1.0\" encoding=\"UTF-8\"";
xml.ResetPos();
xml.InsertNode( xml.MNT_PROCESSING_INSTRUCTION, strDeclData );

You can actually specify it or modify it in pieces too.

xml.ResetPos();
if ( ! xml.FindNode(xml.MNT_PROCESSING_INSTRUCTION) )
    xml.InsertNode( xml.MNT_PROCESSING_INSTRUCTION, "xml" );
xml.SetAttrib( "version", "1.0" );
xml.SetAttrib( "encoding", "UTF-8" );

CMarkup Developer License

More ways to manipulate the XML Declaration are provided by GetDeclaredEncoding and MARKUP_VERSIONTAG (see x_VERSIONTAG in the source code) in CMarkup Developer.

 

comment posted After Use SetDoc, Always "no root element"

David Odi 21-Jul-2005

Created new XML

m_Mark.SetDoc(_T("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"));
m_Mark.AddElem("PATTERN");

then.. always the value of CMarkup::m_strError is "no root element"

Yes, when you initialize the document to just the XML declaration, it sets the error string to reflect the fact that there is no element. No cause for alarm. The error string in CMarkup lingers after an error condition until the next parse, even when a subsequent call resolves the error condition. GetError is most useful immediately after the CMarkup object is instantiated or SetDoc or Load.