ic3man7019
ic3man7019

Reputation: 711

How can I serialize data to XML without .xsd schema?

I am writing an ASP.NET MVC (5) application in which I need to do some custom XML serialization. Before I go on, I should mention that I wasn't exactly sure if this question belongs here or on another forum. If this question would be better suited somewhere else, please let me know. I'll gladly move it.

Software overview:

I have a view that has a form for the user to fill out. When the user fills out the required fields and clicks the submit button, the information in the form should be serialized to XML (based on certain XML requirements), and posted to a URL. That's pretty simple for some, I'm sure. I have very little experience doing this sort of thing in ASP.NET MVC.

I don't possess the .xsd document that contains the XML schema. I have a document that contains the XML specifics (a Word document), but the actual .xsd document is not available to me. I am not sure how to serialize the data so that the XML turns out the way it is supposed to.

I have the following Model:

public class BookingRequest
    {
        public string billTo { get; set; }
        public string bookingStatus { get; set; }
        public string partNote { get; set; }
        public int height { get; set; }
    }

Note that this is an abbreviated version; there are WAY more fields in this class. Anyway, I need the height field to look like this when it is serialized to XML:

<HeightOf>15</HeightOf>

I also need all of the elements in the XML to adhere to this schema (where all of the fields in the form I mentioned fall under the <BookingRequest> tag):

<Data>
    <Header>
        <UserId/>
        <Password/>
    </Header>
    <BookingRequest>
            ..
            ..
    </BookingRequest>
</Data>

Can I do this without the schema?

Any help is greatly appreciated.

Upvotes: 0

Views: 185

Answers (1)

Oscar
Oscar

Reputation: 13980

You don't need the xsd, as long as you know how is going to be the desired structure. First, you need to decorate your class with the [Serializable] attribute. Then, you can use the attributes in System.Xml.Serialization namespace to control the result. For example, in case of height property, it can be achieve like this:

[Serializable]
public class BookingRequest
{
    public string billTo { get; set; }
    public string bookingStatus { get; set; }
    public string partNote { get; set; }
    [XmlElement(ElementName = "HeightOf")]
    public int height { get; set; }
}

See this for further details:

https://learn.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes

Upvotes: 1

Related Questions