保存没有结束标记的IXMLDOMDocument

时间:2009-04-08 19:58:19

标签: c++ xml msxml ixmldomdocument

通过C ++使用MSXML,当我调用IXMLDOMDocument::save时,空XML元素将得到一个结束标记,如下所示:

<root>
    <child name="first">
    </child>
</root>

但是我希望它保存为:

<root>
    <child name="first" />
</root>

我需要做些什么才能实现这一目标?

1 个答案:

答案 0 :(得分:1)

如果没有子节点,DOM本身会这样做,但我不知道为什么在你的情况下它会这样做。 如果你想在DOM指针上显式调用Pretty Print。

#include <msxml2.h>

bool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream)
{

     // Create the writer
     CComPtr <IMXWriter> pMXWriter;
    if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL)))
    {
        return false;
    }
    CComPtr <ISAXContentHandler> pISAXContentHandler;
    if (FAILED (pMXWriter.QueryInterface(&pISAXContentHandler)))
    {
        return false;
    }
    CComPtr <ISAXErrorHandler> pISAXErrorHandler;
    if (FAILED (pMXWriter.QueryInterface (&pISAXErrorHandler)))
    {
        return false;
    }
    CComPtr <ISAXDTDHandler> pISAXDTDHandler;
    if (FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler)))
    {
        return false;
    }

   if (FAILED (pMXWriter ->put_omitXMLDeclaration (VARIANT_FALSE)) ||
       FAILED (pMXWriter ->put_standalone (VARIANT_TRUE)) ||
       FAILED (pMXWriter ->put_indent (VARIANT_TRUE)) ||
       FAILED (pMXWriter ->put_encoding (L"UTF-8")))
   {
       return false;
   }

   CComPtr <ISAXXMLReader> pSAXReader;
   if (FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL)))
   {
      return false;
   }

   if (FAILED (pSAXReader ->putContentHandler (pISAXContentHandler)) ||
    FAILED (pSAXReader ->putDTDHandler (pISAXDTDHandler)) ||
    FAILED (pSAXReader ->putErrorHandler (pISAXErrorHandler)) ||
    FAILED (pSAXReader ->putProperty (
    L"http://xml.org/sax/properties/lexical-handler", CComVariant (pMXWriter))) ||
    FAILED (pSAXReader ->putProperty (
    L"http://xml.org/sax/properties/declaration-handler", CComVariant (pMXWriter))))
   {
      return false;
   }

   // Perform the write

   return SUCCEEDED (pMXWriter ->put_output (CComVariant (pStream))) &&
   SUCCEEDED (pSAXReader ->parse (CComVariant (pDoc)));
}