Saving a IXMLDOMDocument without end tag

人走茶凉 提交于 2019-12-08 06:21:16

问题


Using MSXML via C++, when I call IXMLDOMDocument::save, empty XML elements will get an end tag, like this:

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

But I want it saved as this:

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

What do I need to do to accomplish that?


回答1:


DOM itself does that if there are no child nodes but I don't know why in your case it is doing like this. If you want to do explicitly call Pretty Print on the DOM pointer.

#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)));
}


来源:https://stackoverflow.com/questions/731574/saving-a-ixmldomdocument-without-end-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!