简体   繁体   中英

XML Serialization, Include encoding info and customized namespace

I am Serializing MyXMLData class by following code

XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData));
FileStream fileStream = new FileStream(fileName, FileMode.Create);
xmlSerializer.Serialize(fileStream, myXMLData);
fileStream.Close();

The output header comes something like

<?xml version="1.0"?>
<MyXMLData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

My questions

1) I would like to include encoding data something like`?xml version="1.0" encoding ="utf-8" ?> . How to do this?

2) I would like to change the namespace and put my own custom namesapace (This is my requirement) instead of xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" , I just want to have something like xmlns="http://www.mydata.org" .

I can read the xml file and replace the contents once it is written, but I would like to know, is there anyway to do this in one step when the xml file is written?

You can do the following steps.
1. To achieve your first requirement:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData));
var fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "filename.xml");
var appendMode = false;
var encoding = Encoding.GetEncoding("UTF-8");
using(StreamWriter sw = new StreamWriter(fname, appendMode, encoding))
{
      xmlSerializer.Serialize(sw, MyXMLData);
}    
  1. To achieve the second requirement

To the constructor of the XMLSerializer class, add the namespace like this:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData), "http://www.mydata.org");

This solution works fine as expected

XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData));

XmlSerializerNamespaces ns1 = new XmlSerializerNamespaces();
ns1.Add("", "http://www.mydata.org");

Encoding encoding = Encoding.GetEncoding("UTF-8");

using (StreamWriter sw = new StreamWriter(fileName, false, encoding))
{
    xmlSerializer.Serialize(sw, myXMLData, ns1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM