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)
Ads by The Lounge