7

I have to produce the following XML

<object>
    <stuff>
        <body>
            <random>This could be any rondom piece of unknown xml</random>
        </body>
    </stuff>
</object>

I have mapped this to a class, with a body property of type string.

If I set the body to the string value: "<random>This could be any rondom piece of unknown xml</random>"

The string gets encoded during serialization. How can I not encode the string so that it gets written as raw XML?

I will also want to be able to deserialize this.

2
  • What language? What platform? Commented Jan 12, 2012 at 10:11
  • Opps, justed added the .NET and C# tags Commented Jan 12, 2012 at 10:16

1 Answer 1

6

XmlSerializer will simply not trust you to produce valid xml from a string. If you want a member to be ad-hoc xml, it must be something like XmlElement. For example:

[XmlElement("body")]
public XmlElement Body {get;set;}

with Body an XmlElement named random with InnerText of "This could be any rondom piece of unknown xml" would work.


[XmlRoot("object")]
public class Outer
{
    [XmlElement("stuff")]
    public Inner Inner { get; set; }
}
public class Inner
{
    [XmlElement("body")]
    public XmlElement Body { get; set; }
}

static class Program
{
    static void Main()
    {
        var doc = new XmlDocument();
        doc.LoadXml(
           "<random>This could be any rondom piece of unknown xml</random>");
        var obj = new Outer {Inner = new Inner { Body = doc.DocumentElement }};

        new XmlSerializer(obj.GetType()).Serialize(Console.Out, obj);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, you seem quite clued up on xml serilization, and chance you can answer: stackoverflow.com/questions/8853082/custom-xml-serialization
Cool solution, even Deserialization works - but what if the random XML is like <a>---</a><a>---</a><b>----</b>? Then it can't be loaded into an XmlDocument. That's what I would need to do - with deserialization.

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.