1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 #include <tools/XmlWriter.hxx>
11 #include <o3tl/make_unique.hxx>
13 #include <libxml/xmlwriter.h>
19 int funcWriteCallback(void* pContext
, const char* sBuffer
, int nLen
)
21 SvStream
* pStream
= static_cast<SvStream
*>(pContext
);
22 return static_cast<int>(pStream
->WriteBytes(sBuffer
, nLen
));
25 int funcCloseCallback(void* pContext
)
27 SvStream
* pStream
= static_cast<SvStream
*>(pContext
);
29 return 0; // 0 or -1 in case of error
32 } // end anonymous namespace
36 XmlWriterImpl(SvStream
* pStream
)
43 xmlTextWriterPtr mpWriter
;
46 XmlWriter::XmlWriter(SvStream
* pStream
)
47 : mpImpl(o3tl::make_unique
<XmlWriterImpl
>(pStream
))
51 XmlWriter::~XmlWriter()
53 if (mpImpl
&& mpImpl
->mpWriter
!= nullptr)
57 bool XmlWriter::startDocument()
59 xmlOutputBufferPtr xmlOutBuffer
60 = xmlOutputBufferCreateIO(funcWriteCallback
, funcCloseCallback
, mpImpl
->mpStream
, nullptr);
61 mpImpl
->mpWriter
= xmlNewTextWriter(xmlOutBuffer
);
62 if (mpImpl
->mpWriter
== nullptr)
64 xmlTextWriterSetIndent(mpImpl
->mpWriter
, 1);
65 xmlTextWriterStartDocument(mpImpl
->mpWriter
, nullptr, "UTF-8", nullptr);
69 void XmlWriter::endDocument()
71 xmlTextWriterEndDocument(mpImpl
->mpWriter
);
72 xmlFreeTextWriter(mpImpl
->mpWriter
);
73 mpImpl
->mpWriter
= nullptr;
76 void XmlWriter::startElement(const OString
& sName
)
78 xmlChar
* xmlName
= xmlCharStrdup(sName
.getStr());
79 xmlTextWriterStartElement(mpImpl
->mpWriter
, xmlName
);
83 void XmlWriter::endElement() { xmlTextWriterEndElement(mpImpl
->mpWriter
); }
85 void XmlWriter::attribute(const OString
& name
, const OString
& value
)
87 xmlChar
* xmlName
= xmlCharStrdup(name
.getStr());
88 xmlChar
* xmlValue
= xmlCharStrdup(value
.getStr());
89 xmlTextWriterWriteAttribute(mpImpl
->mpWriter
, xmlName
, xmlValue
);
94 void XmlWriter::attribute(const OString
& name
, const OUString
& value
)
96 attribute(name
, OUStringToOString(value
, RTL_TEXTENCODING_UTF8
).getStr());
99 void XmlWriter::attribute(const OString
& name
, const sal_Int32 aNumber
)
101 attribute(name
, OUString::number(aNumber
));
104 void XmlWriter::content(const OString
& sValue
)
106 xmlChar
* xmlValue
= xmlCharStrdup(sValue
.getStr());
107 xmlTextWriterWriteString(mpImpl
->mpWriter
, xmlValue
);
111 void XmlWriter::content(const OUString
& sValue
)
113 content(OUStringToOString(sValue
, RTL_TEXTENCODING_UTF8
));
116 void XmlWriter::element(const OString
& sName
)
122 } // end tools namespace
124 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */