9

Is there an equivalent library for JAXB in .NET? I am trying to convert an XML I get to a .NET class. I have the XSD, but not sure how to convert the XML received into a concrete Class? I used the XSD tool to generate a class from the schema, but what I want to to convert the XML I receive on the fly to a object that I can work with in code.

I've seen the thread here that deals with this, but my query is - I want the object created to contain the data that I receive in the XML (i.e. the field values must be populated).

Community
  • 1
  • 1
Joseph
  • 2,155
  • 6
  • 20
  • 32

2 Answers2

10

You can use xsd.exe to generate the class and then use XmlSerializer in your code to populate the class. For example if xsd.exe creates a class called Foo you could write:

Foo someFoo;
using (var stream = new FileStream("foo.xml", FileMode.Open))
{
    var serializer = new XmlSerializer(typeof(Foo));
    someFoo = serializer.Deserialize(stream);
}
Mike Two
  • 44,935
  • 9
  • 80
  • 96
0

This is a much better way and more closer to what I was looking for:

static public string serializeObject(ProductPriceLines objecteToSerialize)
    {
        System.Xml.Serialization.XmlSerializer mySerializer = new System.Xml.Serialization.XmlSerializer(typeof(ProductPriceLines));

        System.IO.MemoryStream t = new System.IO.MemoryStream();
        mySerializer.Serialize(t, objecteToSerialize);


        UTF8Encoding utf = new UTF8Encoding();
        string strbytes = utf.GetString(t.ToArray());


        return strbytes;
    }
Joseph
  • 2,155
  • 6
  • 20
  • 32
  • 2
    Not saying you're wrong, just curious why this solution is better than Mike Two's. +1 once you respond. – JagWire Sep 16 '13 at 18:05
  • 2
    Your question asks for XML => object. Your answer does it the other way around: object => XML. – ViToni Feb 04 '15 at 11:21