.comment-link {margin-left:.6em;}

Ben Cops

Monday, July 05, 2004

Save an XML Document to a stream without the XML declaration

This is really handy if you feel the encoding attribute of the XML declaration you're forced to accept from XMLDocument.Save() is causing you grief:
GotDotNet User Sample: XmlFragmentWriter for Xml Serialization

Basically it uses reflection to set a private field on an XMLTextWriter to fool the writer into thinking its already written the declaration. Naughty!


// get to the currentState field
Type xmlTextWriterType = typeof( System.Xml.XmlTextWriter );
FieldInfo currentStateFieldInfo = xmlTextWriterType.GetField(
"currentState", BindingFlags.Instance | BindingFlags.NonPublic );

// get the State enumeration
Type stateEnumType = xmlTextWriterType.GetNestedType( "State",
BindingFlags.NonPublic );

// set the currentState to Prolog written
currentStateFieldInfo.SetValue( this,
stateEnumType.GetField( "Prolog" ).GetValue( this ) );

29 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home