XmlWriter including namespace\schema for each tag

I need to create a file in XML using XmlWriter including for each tag the namespace\schema. First I have a class produced by xsd schema file, I create the class with all objects and finally I serialize the class writing xml:

myclass root = new myclass();
root.val1 = "temp1";
root.val2 = "temp2";

[...]

using (XmlWriter writer = XmlWriter.Create(Path.Combine("myfile.xml"), s))
{
    serializer.Serialize(writer, root);

the problem is that it creates the tags like that:

<Message>
    <val1> temp1 </val1>
    <val2> temp2 </val2>
<Message>

I want to write the tags as:

<temp:Message>
    <temp:val1> temp1 </val1>
    <temp:val2> temp2 </val2>
<temp:Message>

can I use some attribute in my class to add temp: starting tags?

I need also to add to my root tag some namespace:

<temp:Message
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="myxml.xsd"
    xmlns:stf="urn:oecd:ties:stf:v4"
    xmlns:mesage="urn:oecd:ties:cbc:v1"
    xmlns:iso="urn:oecd:ties:isocbctypes:v1"
    version="1.0"> 

so I need to add to root class:

1) xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2) xsi:schemaLocation="myxml.xsd"
3) xmlns:mesage="urn:oecd:ties:cbc:v1"
4) etc...

how can I do that?

728x90

1 Answers XmlWriter including namespace\schema for each tag

you can attache temp by doing as below , attach namespace with you xml

var xsn = new XmlSerializerNamespaces();
xsn.Add("temp", "http://namespaceforxml");
XmlSerializer s = new XmlSerializer(typeof(Message));
Message msg = new Message(); 
// Writing a file requires a TextWriter.
TextWriter t = new StreamWriter(filename);
s.Serialize(t,msg,ns);
t.Close();

decorate calss as below

[XmlRoot(ElementName = "Message", Namespace = "//namespaceforxml")]
public class Message
{
    [XmlElement(ElementName = "val1")]
    public string val1{ get; set; }
}

1 year ago