Implementing IXmlWriter Part 3: Supporting WriteElementString()
Implementing IXmlWriter c++ ixmlwriter xml
Published: 2005-10-07
Implementing IXmlWriter Part 3: Supporting WriteElementString()

This is part 3/14 of my Implementing IXmlWriter post series.

Today’s addition to the previous iteration of IXmlWriter is quite trivial: supporting the WriteElementString() method.

Here’s the test case:

1
2
3
4
5
6
7
StringXmlWriter xmlWriter;
xmlWriter.WriteStartElement("root");
  xmlWriter.WriteElementString("element", "value");
xmlWriter.WriteEndElement();

std::string strXML = xmlWriter.GetXmlString();
// strXML should be <root><element>value</element></root>

Implementation is extremely simple because WriteElementString() is nothing but a convenience method which calls WriteStartElement(), WriteString(), and WriteEndElement(). Therefore, here’s the new StringXmlWriter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class StringXmlWriter
{
private:
    std::stack<std::string> m_openedElements;
    std::string m_xmlStr;

public:
    void WriteStartElement(const std::string& localName)
    {
        m_openedElements.push(localName);
        m_xmlStr += '<';
        m_xmlStr += localName;
        m_xmlStr += '>';
    }

    void WriteEndElement()
    {
        std::string lastOpenedElement = m_openedElements.top();
        m_xmlStr += "</";
        m_xmlStr += lastOpenedElement;
        m_xmlStr += '>';
        m_openedElements.pop();
    }

    void WriteString(const std::string& value)
    {
        typedef std::string::const_iterator iter_t;
        for (iter_t iter = value.begin(); iter != value.end(); ++iter) {
            if (*iter == '&') {
                m_xmlStr += "&amp;";
            } else if (*iter == '<') {
                m_xmlStr += "&lt;";
            } else if (*iter == '>') {
                m_xmlStr += "&gt;";
            } else {
                m_xmlStr += *iter;
            }
        }
    }

    void WriteElementString(const std::string& localName,
                            const std::string& value)
    {
        WriteStartElement(localName);
        WriteString(value);
        WriteEndElement();
    }

    std::string GetXmlString() const
    {
        return m_xmlStr;
    }
};