Using the XmlSerializer to Read and Write XML Fragments

This may not be interesting to you if you don't like the XmlSerializer. I use it for lots of stuff and I'm currently using it in the middle of an XmlReader/XmlWriter pipeline to grab off little object chunks via reader.ReadOuterXml (a .NET 1.1's poorman's ReadSubTree). I've got schemas for my objects that they are generated from, and as schema, they have namespaces. However, the Xml Fragments I'm grabbing off do not have namespaces, and sometimes the document doesn't (don't ask, sometimes life doesn't turn out how you'd like, eh?).

So, I need to be able to read and write Xml Fragments into and out of objects via the XmlSerializer. This uses a view techniques I've covered before like the XmlFragmentWriter (Yes there are other ways) and the XmlNamespaceUpgradeReader. I added a few properties like SuppressAllNamespaces and JustRoot to really make these bare XmlFragments.

[Test]

public void TestRoundTrip()

{

    AccountType acct = new AccountType();

    acct.AvailableBalance = 34.33M;

    acct.AvailableBalanceSpecified = true;

    acct.Number = "54321";

    acct.Description = "My Checking";

 

    XmlSerializer ser = new XmlSerializer(typeof(AccountType));

 

    //***WRITE***

    StringBuilder sb = new StringBuilder();

    using(StringWriter sw = new StringWriter(sb))

    {

        XmlFragmentWriter fragWriter = new XmlFragmentWriter(sw);

        fragWriter.SuppressAllNamespaces = true;

        ser.Serialize(fragWriter,acct);

        fragWriter.Close();

    }

 

    string result = sb.ToString();

 

    //***READ***

    AccountType acctReborn = null;

    using(StringReader sr = new StringReader(result))

    {

        acctReborn = ser.Deserialize(

            new XmlNamespaceUpgradeReader(sr,

            String.Empty,

            "http://banking.corillian.com/Account.xsd")) as AccountType;

    }

 

    Assert.IsTrue(acctReborn.AvailableBalance == 34.33M);

}

Enjoy, improve, give back. File Attachment: SerializationFragmentTest.zip (5 KB)

Tracked by:
"[Links] Einige interessante Links am Sonntag" (Damir Tomicic : ein Tag in der C... [Trackback]
http://progcbearsedev/dasblog/2006/02/15/linksFor20060215.aspx [Pingback]
Wednesday, February 15, 2006 2:21:19 AM UTC
So the problem wasn't with the XmlNamespaceUpgradeReader but the incoming data?
Friday, February 17, 2006 5:46:55 AM UTC
It was actually that arrays of elements often get a "free" wrapper element like ArrayOfFoo that isn't in the original namespace/xsd. So, you get

[root]
[arrayoffoo]
[foo]
etc

And the arrayoffoo gets upgraded by the reader, and the serializer isn't reader for it. I'm punting on that for now.
Scott Hanselman
Comments are closed.
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.