How to add namespace when doing XmlSerialization using XmlWriter?

I use XmlWriter in conjunction with Xml Serialization. I can output the XML perfectly, but how to enable the xmlns attribute with XmlWriter seems to have eluded me.

To record the beginning of a document, I use the following:

Writer.WriteStartDocument(); Writer.WriteStartElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9"); 

With the XmlWriter that I created, I then go through SitemapNodes, I created them and write them to the base string constructor using serialization as follows:

  foreach (uk.co.andrewrea.SitemapNode node in List) { Serializer.Serialize(Writer, node); } 

As I said, this works fine, but the specified namespace for the root element is not included. Every time I try to physically write an attribute, xmlns, I get an exception that xmlns is reserved by the system for using XML, so basically I can not use it.

I know how to do this with XmlTextWriter and also with the XmlDocument class, but I need to understand how I achieve this using XmlWriter and through serialization.

The following attempt also throws an exception from the reserved namespace.

 foreach (uk.co.andrewrea.SitemapNode node in List) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"); Serializer.Serialize(Writer, node, ns); } Exception Details: System.ArgumentException: Prefix "xmlns" is reserved for use by XML. 
+3
source share
1 answer

You can add a namespace to the XmlSerialization attributes, for example:

 [XmlElement( ElementName = "Members", Namespace = "http://www.cpandl.com")] public Employee[] Employees; 

if you have control over the code.

+4
source

Source: https://habr.com/ru/post/1432773/


All Articles