I’ve a little library that build excel files in openXml format. It is based on LINQ to XML, and permits you to open an excel file with open xml sdk, then manipulate the content and showing it to the user.

Today for a particular set of data I got

hexadecimal value 0x0C, is an invalid character

This is a standard error of Xml, due to the fact that there are some character in ASCII set that cannot be included in XML content. Since I read data from a db, it happens that some strings contain char 0x0C ( f ). To accomplish  this with the minimum effort I simply write such a class

class SanitizedXmlWriter : XmlWriter
{
    private XmlWriter wrapped;

    public SanitizedXmlWriter(XmlWriter wrapped)
    {
        this.wrapped = wrapped;
    }

    public override void Close()
    {
        wrapped.Close();
    }

This is a simple wrapper for an XmlWriter, since I got this error when I try to write to a XmlWriter an XElement that contains those non valid chars. All functions are simple wrappers of base class except that one that write  a string.

public override void WriteString(string text)
{
    if (text.All(c => IsValidXmlChar(c)))
    {
        wrapped.WriteString(text);
    }
    else
    {
        StringBuilder sb = new StringBuilder(text.Length);
        foreach (char c in text)
        {
            if (IsValidXmlChar(c))
                sb.Append(c);
        }
        wrapped.WriteString(sb.ToString());
    }
}

The first test verify if All characters in input string are valid chars, if yes I can simply use base function, while if there is a single invalid chars, I need to copy all chars into a temp string builder, discarding invalid chars. Now I can use whenever I write XElement to a XmlWriter

using (Stream s = workbookPart.SharedStringTablePart.GetStream(FileMode.Create, FileAccess.Write))
{
    using (XmlWriter xmlw = new SanitizedXmlWriter(XmlWriter.Create(s)))
    {
        XmlSharedString.WriteTo(xmlw);
    }

Et voilà, now everything works ok again.

Alk.

Tags:

kick it on DotNetKicks.com

One Response to “XElement and hexadecimal value 0x0C is an invalid character”

  1. What would it take to get the source of your “little library that build excel files”? I was intrigued by your previous blog post about injecting data into an xlsx and updating charts. I have a very similar need (injecting data, then updating pivot tables). This is from your November 28 2008 blog entry.

    I was able to get the source to the ExcelFiller as there was a link to it. But it references other custom namespaces that are not included (ActValue.OpenXml.OpenXmlParts).

    What are the odds you could post your library? Codeplex seems a good place :)