Re: [xml] xmlSaveToFd: unexpected behavior while redirecting the 'stdout' stream to a file



Thanks, indeed the 'xmlSaveToFilename' function is what I was looking for.

Here is the code:
---
#include <libxml/xmlsave.h> /* for xmlSaveToFilename */
#include <stdio.h> /* for printf */
#include <string.h> /* for strlen */
int main()
{
        const char *str = "<html 
xmlns=\"http://www.w3.org/1999/xhtml\";>\n<head>\n<title>test</title>\n</head>\n<body>\n<p>test</p>\n</body>\n</html>\n";
        xmlSaveCtxtPtr ctxt = NULL;
        xmlDocPtr doc = NULL;
        printf("Content-Type: application/xhtml+xml;\n\n");
        doc = xmlParseMemory(str, strlen(str) + 1);
        ctxt = xmlSaveToFilename("-", NULL, XML_SAVE_FORMAT);
        if(ctxt == NULL)
        {
                fprintf(stderr, "Unable to create the document saving context.\n");
                exit(EXIT_FAILURE);
        }
        if(xmlSaveDoc(ctxt, doc) == -1)
        {
                fprintf(stderr, "Unable to save the document to the document saving context.\n");
                exit(EXIT_FAILURE);
        }
        if(xmlSaveClose(ctxt) == -1)
        {
                fprintf(stderr, "Unable to close the document.\n");
                exit(EXIT_FAILURE);
        }
        xmlFreeDoc(doc);
        xmlCleanupParser();
        exit(EXIT_SUCCESS);
}
---

Here is the expected behavior while redirecting the 'stdout' stream to a file:
---
$ ./main.out 1>1.txt
$ cat 1.txt 
Content-Type: application/xhtml+xml;

<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml";>
<head>
<title>test</title>
</head>
<body>
<p>test</p>
</body>
</html>
---

Problem solved!

On Wed, 4 Apr 2018 13:37:23 +0200
Nick Wellnhofer <wellnhofer aevum de> wrote:

On 04/04/2018 13:28, YuGiOhJCJ Mailing-List wrote:
In order to use buffered IO only, I am now using the 'xmlSaveFile' function (instead of 'xmlSaveToFd'):

However, with this solution, I loose the 'options' parameter that was available with the 'xmlSaveToFd' 
function.
Is there a similar solution with the 'options' parameter please?

You can use xmlSaveToFilename with "-" as filename. There's also xmlSaveToIO 
taking custom IO callbacks.

Nick


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]