开发者

DOMDocument to string xerces-c

开发者 https://www.devze.com 2023-01-29 07:03 出处:网络
I have a parsed an XML document with xerces-c and can successfully write it to a file like the DOMPrint example, but I can not store this in an array.I see online that I should still use a serializer,

I have a parsed an XML document with xerces-c and can successfully write it to a file like the DOMPrint example, but I can not store this in an array. I see online that I should still use a serializer, but I'm no开发者_JAVA技巧t sure what to change. Obviously, instead of using a LocalFileFormatTarget, I should use something else, but looking online for a reference on MemBufFormatTarget gives no clue on how to use it. How can I get a xml document to a string with xerces-c?


Use a XMLFormatTarget class like this one to get the output into a buffer of characters:

class LStringXMLFormatTarget : public XMLFormatTarget
{
public:
LStringXMLFormatTarget()
{
    m_pBuffer = NULL;
    m_nTotal = 0;
}

char*       GetBuffer()
{
    return m_pBuffer;
}

ULONG       GetLength()
{
    return m_nTotal;
}

virtual void writeChars(const XMLByte* const toWrite, const XMLSize_t count, XMLFormatter* const formatter)
{
    if(toWrite)
    {
        char*   pTmp = new char[m_nTotal + count + 1];

        if(m_pBuffer)
        {
            memcpy(pTmp, m_pBuffer, m_nTotal);
            delete m_pBuffer;
        }

        memcpy(&pTmp[m_nTotal], toWrite, count);

        m_nTotal += count;
        m_pBuffer = pTmp;

        if(m_pBuffer)
            m_pBuffer[m_nTotal] = 0;
    }
}

protected:
    char*       m_pBuffer;
    ULONG       m_nTotal;
};

Please note that this is by intention a buffer of single characters because the output encoding could also consist of multi-byte characters.

Use it together with the DOMLSOutput and DOMLSSerializer objects:

DOMLSOutput*  pLSOutput = impl->createLSOutput();

if(pLSOutput)
{
    pLSOutput->setByteStream(&stringTarget);
    pSerializer->write(doc, pLSOutput);
}

p.s. Please note that for a more efficient implementation of writeChars() don't copy and allocate always a new buffer but instead you might reserve a large enough memory block before or write to several chunks of memory... This implementation here is just to show how XMLFormatTarget works.

0

精彩评论

暂无评论...
验证码 换一张
取 消