views:

26

answers:

1

Hi everyone,

I'm working in Visual Studio 2008 using c#.

Let's say I have 2 xsd files e.g "Envelope.xsd" and "Body.xsd"

I create 2 sets of classes by running xsd.exe, creating something like "Envelope.cs" and "Body.cs", so far so good.

I can't figure out how to link the two classes to serialize (using XmlSerializer) into the proper nested xml, i.e:

I want: <Envelope><DocumentTitle>Title</DocumentTitle><Body>Body Info</Body></Envelope>

But I get: <Envelope><DocumentTitle>Title</DocumentTitle></Envelope><Body>Body Info</Body>

Could someone perhaps show me how the two .cs classes should look to enable XmlSerializer to runt the desired nested result?

Thanks a million

Paul

A: 

This ought to do it (sample console program):

using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApplication9
{
    [XmlRoot("Envelope")]
    public class EnvelopeClass
    {
        [XmlElement("DocumentTitle")]
        public string DocumentTitle { get; set; }

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

    public class BodyClass
    {
        [XmlText()]
        public string Body { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EnvelopeClass envelope =
                new EnvelopeClass
                {
                    DocumentTitle = "Title",
                    BodyElement = new BodyClass { Body = "Body Info" }
                };

            XmlSerializer xs = new XmlSerializer(typeof(EnvelopeClass));

            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);
            xs.Serialize(writer, envelope);
            Console.WriteLine(sb.ToString());
            Console.ReadLine();
        }
    }
}

The resulting output:

    <?xml version="1.0" encoding="utf-16"?>
    <Envelope 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
      <DocumentTitle>Title</DocumentTitle>
      <Body>Body Info</Body>
    </Envelope>

Hope that helps! Remember to mark my post answered pleez... :)

code4life
Thank you, yes it is exactly what I needed.
Paul Connolly