Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# object to XML

I am creating an application which requires to convert c# object to XML.

I am using XML Serializer class to achieve this. Here is the code snippet:

public  class Anwer
{
    public int ID { get; set; }
    public string XML { get; set; }
    public Anwer(int ID, string XML)
    {
        this.ID = ID;
        this.XML = XML;
    }
    public Anwer() { }
}

Here is the main function:

   string AnswerXML = @"<Answer>1<Answer>";
   List<Anwer> answerList = new List<Anwer>();
   answerList.Add(new Anwer(1,AnswerXML));
   AnswerXML = @"<Answer>2<Answer>";
   answerList.Add(new Anwer(2, AnswerXML));
   XmlSerializer x = new XmlSerializer(answerList.GetType());
   x.Serialize(Console.Out, answerList);

The output is:

<?xml version="1.0" encoding="IBM437"?>
<ArrayOfAnwer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="h
ttp://www.w3.org/2001/XMLSchema">
  <Anwer>
    <ID>1</ID>
    <XML>&lt;Answer&gt;1&lt;Answer&gt;</XML>
  </Anwer>
  <Anwer>
    <ID>2</ID>
    <XML>&lt;Answer&gt;2&lt;Answer&gt;</XML>
  </Anwer>
</ArrayOfAnwer>

In the above code '<' and '>' are getting replaced by '<' and '&gt'; How to avoid this? I know string replace is one of the way, but I don't want to use it.

Thanks in advance.

like image 809
Amit Shah Avatar asked Dec 12 '22 17:12

Amit Shah


1 Answers

You don't, basically. That's correctly serializing the object - the XML serializer doesn't want to have to deal with XML within strings messing things up, so it escapes the XML appropriately.

If you deserialize the XML later, you'll get back to the original object data.

If you're trying to build up an XML document in a custom fashion, I suggest you don't use XML serialization to start with. Either use LINQ to XML if you're happy to create elements etc explicitly, or if you really, really want to include arbitrary strings directly in your output, use XmlWriter.

If you could give us more information about the bigger picture of what you're trying to do, we may be able to suggest better alternatives - building XML strings directly is almost never a good idea.

like image 161
Jon Skeet Avatar answered Dec 25 '22 05:12

Jon Skeet