Reputation: 663
So I have searched all I can, but cannot find the exact problem I am encountering.
This is my nested XML:
<Message>
<Foo>
<Bar>1</Bar>
<Baz>2</Baz>
<Qux>3</Qux>
</Foo>
</Message>
And I have a class in C#:
[Serializable()]
[XmlRoot("Message")]
public class Foo
{
[XmlElement("Bar")]
public string Bar { get; set; }
[XmlElement("Baz")]
public string Baz { get; set; }
[XmlElement("Qux")]
public string Qux { get; set; }
}
Now Message is just arbitrary and gets sent with every XML message. So every XML message sent will have a <Message>
tag around it. When I put Foo
as the XmlRoot
it throws an error, and with Message
as XmlRoot
it doesn't recognize the child elements. I am looking for a clean and easy solution to this. Thanks!
Upvotes: 0
Views: 246
Reputation: 164
Use to get correct model here link
After that you can these methods to serialize and deserialize:
public static class XMLFactory
{
public static T XmlDeserializeFromString<T>(this string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static object XmlDeserializeFromString(this string objectData, Type type)
{
try
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
catch (Exception ex)
{
LoggerHelper.LogError(ex.ToString());
return null;
}
}
public static string XmlSerializeToString(this object objectInstance)
{
var serializer = new XmlSerializer(objectInstance.GetType());
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectInstance);
}
return sb.ToString();
}
}
Upvotes: 1
Reputation: 17145
I haven't tested this, but it should work.
[Serializable()]
[XmlRoot("Message")]
public class Message
{
[XmlElement("Foo")]
public Foo Foo { get; set; }
}
[Serializable()]
public class Foo
{
[XmlElement("Bar")]
public string Bar { get; set; }
[XmlElement("Baz")]
public string Baz { get; set; }
[XmlElement("Qux")]
public string Qux { get; set; }
}
Upvotes: 1