[quoted text, click to view] "Bill Geake" <geakewil@hotmail.com> wrote in message news:12e3b334.0409081513.2d97cc28@posting.google.com...
> However, for my real world application, subThing is defined in another
> namespace. When I am done, my resulting file needs to look like this:
: :
> Note the additional namespace declaration in the root element, along
> with the qualified names in subThing. This is relatively easy when
> creating an XML Document from scratch with the CreateAttribute()
> method, however since I am serializing from a class, how can I
> accomplish this?
Add XmlElementAttributes to the properties of subThing belonging
to this second namespace. XmlElementAttributes allow you to
customize the ElementName, Namespace (URI), and other
properties of how the property/field gets serialized.
public class subClassDataType
{
[XmlElement( Namespace="somethingelse")]
public string subThingElement1;
[XmlElement( Namespace="somethingelse")]
public string subThingElement2;
}
This produces a document that ought to be equivalent to
your requirements, but if you want to manifest additional
control that guarantees the ns2 prefix is used, it would
be necessary that an XmlSerializerNamespaces gets
created, has the "ns2" prefix (associated of course with the
same Namespace URI you've given to these child elements
of subThing) added to it, and is passed to the XmlSerializer
when you call Serialize( ).
// Create XmlSerializer for your Type.
XmlSerializer mySerializer = new XmlSerializer(typeof(testClass));
// Create an XmlSerializerNamespaces to control the prefixes
// that get generated for namespace URIs appearing in the
// serialized XML.
XmlSerializerNamespaces myNamespaces = new
XmlSerializerNamespaces( );
// Associate ns2 with the namespace URI used for subThing's
// child elements.
myNamespaces.Add( "ns2", "somethingelse");
// When using XmlSerializerNamespaces, you must specify xsi
// and xsd namespace declarations if you want them.
myNamespaces.Add( "xsi", "
http://www.w3.org/2001/XMLSchema-instance");
myNamespaces.Add( "xsd", "
http://www.w3.org/2001/XMLSchema");
// Create a StreamWriter to write the XML serialization to.
StreamWriter myWriter = new StreamWriter("test3.xml");
// Serialize the instance, c, using the XmlSerializerNamespaces.
mySerializer.Serialize( myWriter, c, myNamespaces);
// Flush and close the StreamWriter to ensure everything gets
// committed to file.
myWriter.Flush( );
myWriter.Close( );
Derek Harmon