1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "third_party/libxml/chromium/xml_writer.h"
6 
7 #include <libxml/xmlwriter.h>
8 
9 #include "third_party/libxml/chromium/libxml_utils.h"
10 
XmlWriter()11 XmlWriter::XmlWriter() : writer_(nullptr), buffer_(nullptr) {}
12 
~XmlWriter()13 XmlWriter::~XmlWriter() {
14   if (writer_)
15     xmlFreeTextWriter(writer_);
16   if (buffer_)
17     xmlBufferFree(buffer_);
18 }
19 
StartWriting()20 void XmlWriter::StartWriting() {
21   buffer_ = xmlBufferCreate();
22   writer_ = xmlNewTextWriterMemory(buffer_, 0);
23   xmlTextWriterSetIndent(writer_, 1);
24   xmlTextWriterStartDocument(writer_, nullptr, nullptr, nullptr);
25 }
26 
StopWriting()27 void XmlWriter::StopWriting() {
28   xmlTextWriterEndDocument(writer_);
29   xmlFreeTextWriter(writer_);
30   writer_ = nullptr;
31 }
32 
StartIndenting()33 void XmlWriter::StartIndenting() {
34   xmlTextWriterSetIndent(writer_, 1);
35 }
36 
StopIndenting()37 void XmlWriter::StopIndenting() {
38   xmlTextWriterSetIndent(writer_, 0);
39 }
40 
StartElement(const std::string & element_name)41 bool XmlWriter::StartElement(const std::string& element_name) {
42   return xmlTextWriterStartElement(writer_, BAD_CAST element_name.c_str()) >= 0;
43 }
44 
EndElement()45 bool XmlWriter::EndElement() {
46   return xmlTextWriterEndElement(writer_) >= 0;
47 }
48 
AppendElementContent(const std::string & content)49 bool XmlWriter::AppendElementContent(const std::string& content) {
50   return xmlTextWriterWriteString(writer_, BAD_CAST content.c_str()) >= 0;
51 }
52 
AddAttribute(const std::string & attribute_name,const std::string & attribute_value)53 bool XmlWriter::AddAttribute(const std::string& attribute_name,
54                              const std::string& attribute_value) {
55   return xmlTextWriterWriteAttribute(writer_, BAD_CAST attribute_name.c_str(),
56                                      BAD_CAST attribute_value.c_str()) >= 0;
57 }
58 
WriteElement(const std::string & element_name,const std::string & content)59 bool XmlWriter::WriteElement(const std::string& element_name,
60                              const std::string& content) {
61   return xmlTextWriterWriteElement(writer_, BAD_CAST element_name.c_str(),
62                                    BAD_CAST content.c_str()) >= 0;
63 }
64 
GetWrittenString()65 std::string XmlWriter::GetWrittenString() {
66   return buffer_ ? internal::XmlStringToStdString(buffer_->content) : "";
67 }
68