1 // Copyright 2019 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef THIRD_PARTY_LIBXML_CHROMIUM_XML_WRITER_H_ 6 #define THIRD_PARTY_LIBXML_CHROMIUM_XML_WRITER_H_ 7 8 #include <string> 9 10 extern "C" { 11 struct _xmlBuffer; 12 struct _xmlTextWriter; 13 } 14 15 // XmlWriter is a wrapper class around libxml's xmlWriter, 16 // providing a simplified C++ API. 17 // StartWriting must be called before other methods, and StopWriting 18 // must be called before GetWrittenString() will return results. 19 class XmlWriter { 20 public: 21 XmlWriter(); 22 ~XmlWriter(); 23 24 // Allocates the xmlTextWriter and an xmlBuffer and starts an XML document. 25 // This must be called before any other functions. By default, indenting is 26 // set to true. 27 void StartWriting(); 28 29 // Ends the XML document and frees the xmlTextWriter. 30 // This must be called before GetWrittenString() is called. 31 void StopWriting(); 32 33 // Wrappers around libxml functions ----------------------------------------- 34 35 // All following elements will be indented to match their depth. 36 void StartIndenting(); 37 38 // All follow elements will not be indented. 39 void StopIndenting(); 40 41 // Start an element with the given name. All future elements added will be 42 // children of this element, until it is ended. Returns false on error. 43 bool StartElement(const std::string& element_name); 44 45 // Ends the current open element. Returns false on error. 46 bool EndElement(); 47 48 // Appends to the content of the current open element. 49 bool AppendElementContent(const std::string& content); 50 51 // Adds an attribute to the current open element. Returns false on error. 52 bool AddAttribute(const std::string& attribute_name, 53 const std::string& attribute_value); 54 55 // Adds a new element with name |element_name| and content |content| 56 // to the buffer. Example: <|element_name|>|content|</|element_name|> 57 // Returns false on errors. 58 bool WriteElement(const std::string& element_name, 59 const std::string& content); 60 61 // Helper functions not provided by xmlTextWriter --------------------------- 62 63 // Returns the string that has been written to the buffer. 64 std::string GetWrittenString(); 65 66 private: 67 // The underlying libxml xmlTextWriter. 68 _xmlTextWriter* writer_; 69 70 // Stores the output. 71 _xmlBuffer* buffer_; 72 }; 73 74 #endif // THIRD_PARTY_LIBXML_CHROMIUM_XML_WRITER_H_ 75