I found a useful code snippet on codeproject that helps reformat XML documents. I am wondering if anyone knows how to adjust the stylesheet so that empty tags in the transformed XML file are displayed as <tag />
instead of <tag></tag>
.
// Here is a piece of code taken from codeproject
MSXML2::IXMLDOMDocumentPtr ModifyXMLTags(MSXML2::IXMLDOMDocumentPtr pDoc)
{
LPCSTR const static szStyleSheet =
R"!(<?xml version="1.0" encoding="utf-8"?>)!"
R"!(<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">)!"
R"!( <xsl:output method="xml" indent="yes"/>)!"
R"!( <xsl:template match="@* | node()">)!"
R"!( <xsl:copy>)!"
R"!( <xsl:apply-templates select="@* | node()"/>)!"
R"!( </xsl:copy>)!"
R"!( </xsl:template>)!"
R"!(</xsl:stylesheet>)!";
MSXML2::IXMLDOMDocumentPtr pXmlStyleSheet;
pXmlStyleSheet.CreateInstance(__uuidof(MSXML2::DOMDocument60));
pXmlStyleSheet->loadXML(szStyleSheet);
MSXML2::IXMLDOMDocumentPtr pXmlFormattedDoc;
pXmlFormattedDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
CComPtr<IDispatch> pDispatch;
HRESULT hr = pXmlFormattedDoc->QueryInterface(IID_IDispatch, (void**)&pDispatch);
if (SUCCEEDED(hr))
{
_variant_t vtOutObject;
vtOutObject.vt = VT_DISPATCH;
vtOutObject.pdispVal = pDispatch;
vtOutObject.pdispVal->AddRef();
hr = pDoc->transformNodeToObject(pXmlStyleSheet, vtOutObject);
}
// Changing the default encoding from UTF-16 to UTF-8
// <?xml version="1.0" encoding="UTF-8"?>
MSXML2::IXMLDOMNodePtr pXMLFirstChild = pXmlFormattedDoc->GetfirstChild();
MSXML2::IXMLDOMNamedNodeMapPtr pXMLAttributeMap = pXMLFirstChild->Getattributes();
MSXML2::IXMLDOMNodePtr pXMLEncodNode = pXMLAttributeMap->getNamedItem(_T("encoding"));
pXMLEncodNode->PutnodeValue(_T("UTF-8"));
return pXmlFormattedDoc;
}