代码之家  ›  专栏  ›  技术社区  ›  Suri

如何使用xmlite将XML存储在缓冲区中?

  •  1
  • Suri  · 技术社区  · 15 年前

    我试图在缓冲区上用xmllite编写XML数据,但没有任何API。写一个XML文件很好,但是在内存流上我无法计算 我正在研究follwong链接API http://msdn.microsoft.com/en-us/library/ms752901(v=VS.85).aspx

    1 回复  |  直到 14 年前
        1
  •  2
  •   Samuel Zhang    15 年前

    你可以使用 SHCreateMemStream CreateStreamOnHGlobal 创建内存流。以下是供您参考的示例代码:

    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接口一起工作。它真的不在乎在场景后面的小溪究竟是什么样子。

    推荐文章