c++ - 如何使用 xmlite 将 xml 存储在缓冲区中?

标签 c++ xmllite

我正在尝试使用 XmlLite 在缓冲区上写入 xml 数据,但无法获得任何 api。写一个 xml 文件很完美,但在内存流上我想不通 我正在研究 follwong link api http://msdn.microsoft.com/en-us/library/ms752901(v=VS.85).aspx

最佳答案

您可以使用 SHCreateMemStreamCreateStreamOnHGlobal创建内存流。以下是供您引用的示例代码:

CComPtr<IStream> spMemoryStream;
CComPtr<IXmlWriter> spWriter;
CComPtr<IXmlWriterOutput> pWriterOutput;

// Opens writeable output stream.
spMemoryStream.Attach(::SHCreateMemStream(NULL, 0));
if (spMemoryStream == NULL)
    return E_OUTOFMEMORY;

// Creates the xml writer and generates the content.
CHKHR(::CreateXmlWriter(__uuidof(IXmlWriter), (void**) &spWriter, NULL));
CHKHR(::CreateXmlWriterOutputWithEncodingName(spMemoryStream,
    NULL, L"utf-16", &pWriterOutput));
CHKHR(spWriter->SetOutput(pWriterOutput));
CHKHR(spWriter->SetProperty(XmlWriterProperty_Indent, TRUE));
CHKHR(spWriter->WriteStartDocument(XmlStandalone_Omit));
CHKHR(spWriter->WriteStartElement(NULL, L"root", NULL));
CHKHR(spWriter->WriteWhitespace(L"\n"));
CHKHR(spWriter->WriteCData(L"This is CDATA text."));
CHKHR(spWriter->WriteWhitespace(L"\n"));
CHKHR(spWriter->WriteEndDocument());
CHKHR(spWriter->Flush());

// Allocates enough memeory for the xml content.
STATSTG ssStreamData = {0};
CHKHR(spMemoryStream->Stat(&ssStreamData, STATFLAG_NONAME));
SIZE_T cbSize = ssStreamData.cbSize.LowPart;
LPWSTR pwszContent = (WCHAR*) new(std::nothrow) BYTE[cbSize + sizeof(WCHAR)];
if (pwszContent == NULL)
    return E_OUTOFMEMORY;

// Copies the content from the stream to the buffer.
LARGE_INTEGER position;
position.QuadPart = 0;
CHKHR(spMemoryStream->Seek(position, STREAM_SEEK_SET, NULL));
SIZE_T cbRead;
CHKHR(spMemoryStream->Read(pwszContent, cbSize, &cbRead));
pwszContent[cbSize / sizeof(WCHAR)] = L'\0';

wprintf(L"%s", pwszContent);

XmlLite 的一个优点是它可以与 IStream 接口(interface)一起使用。它真的不关心流在幕后究竟是什么样子。

关于c++ - 如何使用 xmlite 将 xml 存储在缓冲区中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3037946/

相关文章:

c++ - 如何激活 TreeView 中的单元格进行编辑

c++ - 编译时 off_t 的大小

c++ - 一个构造函数可以处理多种类型的不同对象参数吗?

c++ - 使用 fstream 将文件数据从当前位置保存到文件末尾

c++ - 使用 XMLString::release( XMLCh ** buf)

c++ - CComPtr 通过引用传递

c++ - XML Lite 解析问题 - 解析时忽略无效数据

c++ - 如何使用 casablanca (PPL) http_client 返回的 XmlLite 处理 XML?