0

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

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

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.