Implementing IXmlWriter Part 12: Supporting Pretty-Printing

This is part 12 of my Implementing IXmlWriter post series.

Today I will add support for pretty-printing to last time’s IXmlWriter.

Pretty-printing is the addition of whitespace at predetermined locations to make the resulting XML easier to read than when it is all on one line. In the .NET Framework’s System.Xml.XmlTextWriter class, it is supported by the properties Formatting, which allows you to enable or disable pretty-printing; Indentation, which allows you to specify how many whitespace characters indentation should use; and IndentChar, which allows you to specify the whitespace character to use for indentation. For IXmlWriter, I instead chose to expose these features exclusively through the constructor. This frees me from the worry of a user trying to change these properties after IXmlWriter has already begun writing XML, which could produce awkward results. Default parameters are used to make the use of pretty-printing optional and straightforward.

I found the easiest way to implement this feature was to construct a complicated test case and then make the code changes accordingly. However, this method is a little disconcerting due to the lack of building a “gut feeling” of correctness. After finishing the code changes, I did a quick review and convinced myself that the logic seems right, but I doubt I will ever grow the same level of confidence that I would have had I built a mental model of the algorithm first.

In addition to pretty-printing, I also rewrote GetNextNamespacePrefix() to find the first available namespace prefix using brute force by trying ns1:, ns2:, … in order rather than using the relationship between namespace prefixes and the number of namespaces already declared. This should make it easier to add user-defined namespace prefixes in the future, as this feature would break the aforementioned relationship.

Here’s the test case:

StringXmlWriter xmlWriter(StringXmlWriter::Formatting_Indented);

xmlWriter.WriteComment("comment");
xmlWriter.WriteStartElement("root");
  xmlWriter.WriteElementString("child", "value");
  xmlWriter.WriteComment("comment");
  xmlWriter.WriteStartElement("child");
    xmlWriter.WriteAttributeString("att", "value");
  xmlWriter.WriteEndElement();
  xmlWriter.WriteStartElement("child");
    xmlWriter.WriteStartElement("child");
      xmlWriter.WriteStartElement("child");
xmlWriter.WriteEndDocument();

std::string strXML = xmlWriter.GetXmlString();

// strXML should equal (whitespace is important):
// <!--comment-->
// <root>
//   <child>value</child>
//   <!--comment-->
//   <child att="value"/>
//   <child>
//     <child>
//       <child/>
//     </child>
//   </child>
// </root>

Here’s the new header file:

// StringXmlWriter.h

class StringXmlWriter
{
public:
    enum Formatting
    {
        Formatting_Indented,
        Formatting_None
    };

    StringXmlWriter(Formatting formatting = Formatting_None,
                    int indentation = 2,
                    char indentChar = ' ');

    std::string GetXmlString() const;
    void WriteAttributeString(const std::string& localName,
                              const std::string& text);
    void WriteAttributeString(const std::string& localName,
                              const std::string& ns,
                              const std::string& text);
    void WriteComment(const std::string& text);
    void WriteElementString(const std::string& localName,
                            const std::string& text);
    void WriteElementString(const std::string& localName,
                            const std::string& ns,
                            const std::string& text);
    void WriteEndAttribute();
    void WriteEndDocument();
    void WriteEndElement();
    void WriteStartAttribute(const std::string& localName);
    void WriteStartAttribute(const std::string& localName,
                             const std::string& ns);
    void WriteStartDocument();
    void WriteStartElement(const std::string& localName);
    void WriteStartElement(const std::string& localName,
                           const std::string& ns);
    void WriteString(const std::string& text);

private:
    // PRIVATE TYPES
    // =============
    enum WriteState
    {
        WriteState_Attribute, // An attribute value is being written
        WriteState_Content, // Element content is being written
        WriteState_Element, // An element start tag has been written (and is unclosed)
        WriteState_Prolog, // The prolog is being written
        WriteState_Start, // No Write() methods have been called
    };

    struct OpenElement
    {
        explicit OpenElement(const std::string& localName) :
            QName(localName)
        {
        }

        explicit OpenElement(const std::string& localName,
                             const std::string& prefix) :
            QName(prefix.empty() ? localName : prefix + ":" + localName)
        {
        }

        // The qualified name (namespace prefix-included) of the
        // opened element
        std::string QName;
        // All namespaces declared in this element (maps namespace
        // to namespace prefix)
        typedef std::map<std::string, std::string> Namespaces_t;
        Namespaces_t Namespaces;
    };

    // PRIVATE FUNCTIONS
    // =================
    std::string GetExistingNamespacePrefix(const std::string& ns);
    std::string GetNextNamespacePrefix(const std::string& ns);
    bool NamespacePrefixExists(const std::string& nsPrefix);
    void CloseOpenElement();
    void NewlineAndIndent();

    // PRIVATE MEMBERS
    // ===============
    WriteState m_writeState;

    // Need to use a vector instead of a stack because we must be able
    // to iterate over each opened element in the stack to see if a
    // namespace has already been declared.
    typedef std::vector<OpenElement> OpenedElements_t;
    OpenedElements_t m_openedElements;

    // Needed to track whether content was written inside the XML element
    // so we know how to handle indentation.
    bool m_contentWritten;

    // The style of formatting we are using.
    Formatting m_formatting;

    // The string to use for a single level of indentation.
    std::string m_indentStr;

    // The XML fragment that this class has generated so far.  There’s no
    // guarantee it will be valid unless WriteEndDocument() is called.
    std::string m_xmlStr;	

private:
    // Disable copy construction and assignment
    StringXmlWriter(const StringXmlWriter&);
    StringXmlWriter& operator=(const StringXmlWriter&);
};

Here’s the new implementation file:

// StringXmlWriter.cpp

#include "StringXmlWriter.h"

#define ARRAYSIZE(x) ( sizeof(x) / sizeof(x[0]) )

struct CharTranslation
{
    char OriginalChar;
    const char* ReplacementString;
};

static const CharTranslation AttributeValueTranslations[] =
{
    { '"', "&quot;" },
    { '&', "&amp;" },
};

static const CharTranslation CharDataTranslations[] =
{
    { '&', "&amp;" },
    { '<', "&lt;" },
    { '>', "&gt;" },
};

struct OriginalCharEquals :
    public std::binary_function<CharTranslation, char, bool>
{
    bool operator() (const CharTranslation& translation, char ch) const
    {
        return (translation.OriginalChar == ch);
    }
};

static std::string TranslateString(const std::string& originalStr,
                                   const CharTranslation* translations,
                                   int numTranslations)
{
    // Actually one past end, needed for proper std::find_if semantics
    const CharTranslation* endTranslations = translations + numTranslations;

    std::string translatedStr;

    for (std::string::const_iterator stringIter = originalStr.begin();
         stringIter != originalStr.end();
         ++stringIter)
    {
        char ch = *stringIter;

        const CharTranslation* translation = std::find_if
            (
            translations,
            endTranslations,
            std::bind2nd(OriginalCharEquals(), ch)
            );
        if (translation != endTranslations)
        {
            translatedStr += translation->ReplacementString;
        }
        else
        {
            translatedStr += ch;
        }
    }

    return translatedStr;
}

StringXmlWriter::StringXmlWriter(Formatting formatting,
                                 int indentation,
                                 char indentChar) :
    m_writeState(WriteState_Start),
    m_formatting(formatting),
    m_contentWritten(false)
{
    for (int i = 0; i < indentation; ++i)
    {
        m_indentStr += indentChar;
    }
}

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

void StringXmlWriter::WriteAttributeString(const std::string& localName,
                                           const std::string& text)
{
    WriteStartAttribute(localName);
    WriteString(text);
    WriteEndAttribute();
}

void StringXmlWriter::WriteAttributeString(const std::string& localName,
                                           const std::string& ns,
                                           const std::string& text)
{
    WriteStartAttribute(localName, ns);
    WriteString(text);
    WriteEndAttribute();
}

void StringXmlWriter::WriteComment(const std::string& text)
{
    switch (m_writeState)
    {
    case WriteState_Element:
        // An element is currently open.  Close the element so we can open
        // a new one.
        CloseOpenElement();
        // FALL THROUGH
    case WriteState_Content:
    case WriteState_Prolog:
    case WriteState_Start:
        if (m_formatting == Formatting_Indented)
        {
            NewlineAndIndent();
        }

        m_xmlStr += "<!–-";
        m_xmlStr += text;
        m_xmlStr += "–->";
        break;
    default:
        // It doesn’t make sense to allow writing comments when writing an
        // attribute value.
        // TODO: Generate error
        break;
    }
}

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

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

void StringXmlWriter::WriteEndAttribute()
{
    switch (m_writeState)
    {
    case WriteState_Attribute:
        m_xmlStr += '"';
        m_writeState = WriteState_Element;
        break;
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteEndDocument()
{
    switch (m_writeState)
    {
    case WriteState_Attribute:
        WriteEndAttribute();
        // FALL THROUGH
    case WriteState_Content:
    case WriteState_Element:
        while (!m_openedElements.empty())
        {
            WriteEndElement();
        }
        break;
    case WriteState_Start:
    case WriteState_Prolog:
        // DO NOTHING
        break;
    default:
        // TODO: Generate error
        break;
    }

    m_writeState = WriteState_Start;
}

void StringXmlWriter::WriteEndElement()
{
    switch (m_writeState)
    {
    case WriteState_Content:
        {
            std::string qname = m_openedElements.back().QName;
            m_openedElements.pop_back();

            if (!m_contentWritten &&
                m_formatting == Formatting_Indented)
            {
                NewlineAndIndent();
            }

            m_xmlStr += "</";
            m_xmlStr += qname;
            m_xmlStr += '>';
            m_writeState = WriteState_Content;
            break;
        }
    case WriteState_Element:
        {
            m_xmlStr += "/>";
            m_openedElements.pop_back();
            m_writeState = WriteState_Content;
            break;
        }
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteStartAttribute(const std::string& localName)
{
    WriteStartAttribute(localName, "");
}

void StringXmlWriter::WriteStartAttribute(const std::string& localName,
                                          const std::string& ns)
{
    switch (m_writeState)
    {
    case WriteState_Element:
        {
        std::string nsPrefix;
        bool mustDeclareNamespace = false;

        if (!ns.empty()) {
            nsPrefix = GetExistingNamespacePrefix(ns);
            if (nsPrefix.empty()) {
                nsPrefix = GetNextNamespacePrefix(ns);
                m_openedElements.back().Namespaces[ns] = nsPrefix;
                mustDeclareNamespace = true;
            }
        }

        if (mustDeclareNamespace) {
            m_xmlStr += " xmlns:";
            m_xmlStr += nsPrefix;
            m_xmlStr += "=\"";
            m_xmlStr += ns;
            m_xmlStr += '"';
        }

        m_xmlStr += ' ';
        if (!nsPrefix.empty()) {
            m_xmlStr += nsPrefix;
            m_xmlStr += ':';
        }
        m_xmlStr += localName;
        m_xmlStr += "=\"";
        m_writeState = WriteState_Attribute;
        break;
        }
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteStartDocument()
{
    switch (m_writeState)
    {
    case WriteState_Start:
        m_xmlStr += "<?xml version=\"1.0\"?>";
        m_writeState = WriteState_Prolog;
        break;
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteStartElement(const std::string& localName)
{
    WriteStartElement(localName, "");
}

void StringXmlWriter::WriteStartElement(const std::string& localName,
                                        const std::string& ns)
{
    switch (m_writeState)
    {
    case WriteState_Element:
        // An element is currently open.  Close the element so we can open
        // a new one.
        CloseOpenElement();
        // FALL THROUGH
    case WriteState_Content:
    case WriteState_Prolog:
    case WriteState_Start:
        {
        if (m_formatting == Formatting_Indented)
        {
            NewlineAndIndent();
        }

        std::string nsPrefix;
        bool mustDeclareNamespace = false;

        if (!ns.empty()) {
            nsPrefix = GetExistingNamespacePrefix(ns);
            if (nsPrefix.empty()) {
                nsPrefix = GetNextNamespacePrefix(ns);
                mustDeclareNamespace = true;
            }
        }

        OpenElement openElement(localName, nsPrefix);
        if (mustDeclareNamespace) {
            openElement.Namespaces[ns] = nsPrefix;
        }

        m_openedElements.push_back(openElement);

        m_xmlStr += '<';
        if (!nsPrefix.empty()) {
            m_xmlStr += nsPrefix;
            m_xmlStr += ':';
        }
        m_xmlStr += localName;
        if (mustDeclareNamespace) {
            m_xmlStr += " xmlns:";
            m_xmlStr += nsPrefix;
            m_xmlStr += "=\"";
            m_xmlStr += ns;
            m_xmlStr += '"';
        }

        m_writeState = WriteState_Element;
        m_contentWritten = false;
        break;
        }
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteString(const std::string& text)
{
    switch (m_writeState)
    {
    case WriteState_Attribute:
        m_xmlStr += TranslateString
            (
            text,
            AttributeValueTranslations,
            ARRAYSIZE(AttributeValueTranslations)
            );
        break;
    case WriteState_Element:
        // An element is currently open.  Close the element so we can start
        // writing the element content.
        CloseOpenElement();
        // FALL THROUGH
    case WriteState_Content:
        m_xmlStr += TranslateString
            (
            text,
            CharDataTranslations,
            ARRAYSIZE(CharDataTranslations)
            );
        m_contentWritten = true;
        break;
    default:
        // TODO: Generate error
        break;
    }
}

std::string StringXmlWriter::GetExistingNamespacePrefix(const std::string& ns)
{
    for (OpenedElements_t::const_iterator openElemIter = m_openedElements.begin();
         openElemIter != m_openedElements.end();
         ++openElemIter)
    {
        OpenElement::Namespaces_t::const_iterator nsIter =
            openElemIter->Namespaces.find(ns);
        if (nsIter != openElemIter->Namespaces.end())
        {
            return nsIter->second;
        }
    }

    return "";
}

std::string StringXmlWriter::GetNextNamespacePrefix(const std::string& ns)
{
    std::string nsPrefix;

    for (int i = 1; ; ++i)
    {
        std::stringstream ss;
        ss << "ns" << i;
        std::string nsPrefix = ss.str();
        if (!NamespacePrefixExists(nsPrefix))
            return nsPrefix;
    }
}

bool StringXmlWriter::NamespacePrefixExists(const std::string& nsPrefix)
{
    for (OpenedElements_t::const_iterator iter = m_openedElements.begin();
         iter != m_openedElements.end();
         ++iter)
    {
        for (OpenElement::Namespaces_t::const_iterator nsIter = iter->Namespaces.begin();
             nsIter != iter->Namespaces.end();
             ++nsIter)
        {
            if (nsIter->second == nsPrefix)
                return true;
        }
    }

    return false;
}

void StringXmlWriter::CloseOpenElement()
{
    m_xmlStr += '>';
    m_writeState = WriteState_Content;
}

void StringXmlWriter::NewlineAndIndent()
{
    assert(m_formatting == Formatting_Indented);

    if (!m_xmlStr.empty())
        m_xmlStr += '\n';

    for (int i = 0; i != m_openedElements.size(); ++i)
    {
        m_xmlStr += m_indentStr;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s