1

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?

1
  • Which language are you using? Java or c#? Commented Apr 24, 2015 at 4:27

2 Answers 2

2

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");

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.