问题描述
我正在使用 MSXML 解析器写出 XML 文件,我从这里下载了一个包装器:http://www.codeproject.com/KB/XML/JW_CXml.aspx.效果很好,除了当我从代码创建一个新文档(所以不是从文件加载和修改)时,结果都在一个大行中.我希望元素能够很好地缩进,以便我可以在文本编辑器中轻松阅读.
I'm writing out XML files using the MSXML parser, with a wrapper I downloaded from here: http://www.codeproject.com/KB/XML/JW_CXml.aspx. Works great except that when I create a new document from code (so not load from file and modify), the result is all in one big line. I'd like elements to be indented nicely so that I can read it easily in a text editor.
谷歌搜索显示许多人有同样的问题 - 大约在 2001 年左右被问到.回复通常说应用 XSL 转换"或添加您自己的空白节点".尤其是最后一个让我去 %( 所以我希望在 2008 年有一种更简单的方法来漂亮的 MSXML 输出.所以我的问题;有吗,我该如何使用它?
Googling shows many people with the same question - asked around 2001 or so. Replies usually say 'apply an XSL transformation' or 'add your own whitespace nodes'. Especially the last one makes me go %( so I'm hoping that in 2008 there's an easier way to pretty MSXML output. So my question; is there, and how do I use it?
推荐答案
试试这个,我多年前在网上发现的.
Try this, I found this years ago on the web.
#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;
}
// Create the SAX reader
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)));
}
这篇关于来自 C++ 的 MSXML - 漂亮的打印/缩进新创建的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!