In this tutorial, I'll show you how to solve XML Serialization and namespace prefixes using XMLSerializer.
<?xml version="1.0" encoding="utf-8"?>
<inv:invoice xmlnss="http://www.w3.org/2000/09/xmldsig#" xmlns:inv="http://c-sharpcode.com/2017/12/invoicexml/v1">
</inv:invoice>
by default you will see your xml element as the following
<?xml version="1.0" encoding="utf-8"?>
<invoice xmlns="http://c-sharpcode.com/2017/12/invoicexml/v1">
</invoice>
To add prefix to your namespace, you can you associate the desired namespace prefixes during serialization by using the XmlSerializerNamespaces class.
You need to generate a class from the xsd file, then your can create the xml file from the class and save it to your hard disk by using the StreamWriter class.
public void Test()
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("ds", "http://www.w3.org/2000/09/xmldsig#");
ns.Add("inv", "http://c-sharpcode.com/2017/12/invoicexml/v1");
var serializer = new XmlSerializer(typeof(invoice));
using (var stream = new StreamWriter(Application.StartupPath + "//mydata.xml"))
{
serializer.Serialize(stream, obj, ns);
}
}
The XmlSerializerNamespaces contains XML namespaces and prefixes that the XmlSerializer uses to generate qualified names in an XML document instance.