Before I explain how to do what you want, it's important to realize that XML readers/parser generally don't care what prefixes you stick on your elements; they only care about the full namespace.
In other words, when your sample XML fragment is loaded, the ns1
bit is completely thrown away. Internally, what you get are XML namespace/element pairs, like ("http://www.opentravel.org/OTA/2003/05", "Response")
or ("http://www.opentravel.org/OTA/2003/05", "Date")
. The reason this is important to know is because you can assign different namespace prefixes to the XML data for use by e.g. XPath, and it will work fine. That is, I could read your XML fragment into my program, and say that "http://www.opentravel.org/OTA/2003/05"
should map to the prefix "t"
, and use XPath like //t:Response
to get the correct results, even though the source XML data had not t
prefix.
In other words, you really, really should not bother trying to get a specific XML namespace prefix into your XML, because it should not matter. If having a specific prefix is necessary for everything to work properly, then someone somewhere is doing something very wrong.
Having said that, if for some reason you need to output specific namespace prefixes, or if you just happen to like the way they look, you can use the XmlSerializerNamespaces
class, as so:
var ns = new XmlSerializerNamespaces();
ns.Add("NS1", "http://www.opentravel.org/OTA/2003/05");
var s = new XmlSerializer(typeof(Response));
var output = new StreamWriter(SOME_FILENAME);
s.Serialize(response, output, ns);
For this to work, you also have to decorate your classes with the full namespace you want them to be in. All of the XML Serializer attributes have a Namespace
parameter you use for this purpose, e.g.:
[XmlRoot(ElementName = "Response",
Namespace = "http://www.opentravel.org/OTA/2003/05")]
public class Response
{
}
When you serialize your object, the serializer will look up the namespaces in the namespace map, and apply the prefix you selected to the appropriate elements.