Reputation: 202
I am trying to generate/serialize an XML file with custom tag in C# and even though I have tried multiple solutions, I have not been able to come up with a valid solution, I will appreciate any contribution. The file should look like:
<?xml version="1.0" encoding="utf-8"?>
<x:Todo>
<Id>1</Id>
<x:UserId>27</UserId>
</Todo>
The issue is I have no idea how to add x: to the tag in specifics nodes.
Thank in advance for all your contributions. Me
Upvotes: 0
Views: 51
Reputation: 3735
You need to define namespace and use it, here is an example (from here):
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Run
{
public static void Main()
{
Run test = new Run();
test.SerializeObject("XmlNamespaces.xml");
}
public void SerializeObject(string filename)
{
XmlSerializer s = new XmlSerializer(typeof(Book));
// Writing a file requires a TextWriter.
TextWriter t = new StreamWriter(filename);
/* Create an XmlSerializerNamespaces object and add two
prefix-namespace pairs. */
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("x", "http://www.cpandl.com");
// Create a Book instance.
Book b = new Book();
b.TITLE = "A Book Title";
s.Serialize(t, b, ns);
t.Close();
}
}
[XmlType(Namespace = "http://www.cpandl.com")]
public class Book
{
[XmlElement(Namespace = "http://www.cpandl.com")]
public string TITLE;
}
Upvotes: 1