Reputation: 1329
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?
Upvotes: 1
Views: 293
Reputation: 1329
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);
}
Upvotes: 0
Reputation: 1191
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);
}
To the constructor of the XMLSerializer class, add the namespace like this:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData), "http://www.mydata.org");
Upvotes: 2