Search code examples
c#xmlfilestreamxmlreadergzipstream

How to read zipped xml from file stream


i've some data to store in an xml file. Easy story! To make it unreadable i've zipped it. This should work fine! But i cant't read the xml content back!

Code i used to write:

using( FileStream fileStream = new FileStream( filepath, FileMode.Create ) ) {
    using( GZipStream zipStream = new GZipStream( fileStream , CompressionMode.Compress ) ) {
        using( XmlWriter xmlWriter = XmlWriter.Create( zipStream, new XmlWriterSettings() { 
            Indent = true, 
            Encoding = Encoding.UTF8, 
            ConformanceLevel = ConformanceLevel.Fragment }
            ) ) {
                xmlWriter.WriteString( xmlDocument.OuterXml );
        }
    }
}

Code i use to read so far:

using( FileStream fileStream = new FileStream( filepath, FileMode.Open ) )
{
    using( GZipStream zipStream = new GZipStream( fileStream , CompressionMode.Decompress ) )
    {
        using( XmlReader xmlReader = XmlReader.Create( zipStream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment } ) )
        {
            xmlReader.MoveToContent();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(xmlReader);
        }
    }
}

But it doesn't work as expected.

The xml file looks quite simple:

<data>
    <name>bill</name>
    <age>45</age>
</data>
<data>
    <name>john</name>
    <age>32</age>
</data>
<data>
    <name>bill</name>
    <age>68</age>
</data>

i'd like to use

XmlNodeList xmlNodeList = xmlDocument.GetElementsByTagName( "data" );

What am i missing? Thank you for any hints.


Solution

  • Inside your read logic replace

    xmlDocument.Load(xmlReader); 
    

    with

    xmlDocument.LoadXml(xmlReader.ReadContentAsString());
    

    This worked for me