Convert an in memory schema-free XmlDocument into a schema-aware (xsd-backed) XmlDocument
I'm trying to write this method:
XmlDocument AddSchemaToRootNode(XmlDocument xmlDocument, string schema) {
}
The input document comes from a expensive-to-change application (written in .Net 2.0). The 开发者_如何学Gooutput is consumed by an XSD-aware XmlSerializer.
I have unit tests that show that I need the xmlns="http://wibble/wobble/wubble" qualifier on the root element in order for the XmlSerializer to work. The untyped-XmlReader doesn't care. How do I get the xmlns qualifier written in?
You need to inject your namespace using XmlAttributeOverrides
. This collection is passed into the XmlSerializer constructor.
To override the root element:
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
var rootNode = new XmlRootAttribute()
{
ElementName = "MyRootNodeName",
Namespace = "http://wibble/wobble/wubble"
};
var newAttribute = new XmlAttributes();
newAttribute.XmlRoot = rootNode;
overrides.Add(typeof(MyType), newAttribute);
To call the serilaizer:
XmlSerializer serializer = new XmlSerializer(typeof(MyType), overrides);
You can also override any other node in the XML using XmlAttributeOverrides. XmlAttributeOverrides is your friend!
Hope this helps.
精彩评论