You could start mapping the classes/attributes/elements:
[Serializable] //Root
[XmlRoot(ElementName = "InfXml", Namespace="the namespace URI")]
public class InfXml
{
[XmlAttribute(AttributeName = "id")] //attribute
public string Id { get; set; }
public bool ShouldSerializeId() //Should serialize, only serializes if not null.
{
return !string.IsNullOrEmpty(Id); //This is only for optional fields.
}
[XmlElement(ElementName = "Identification")] //Non optional group.
public Identification Identification{ get; set; }
[XmlElement(ElementName = "Adress")] //Optional group.
public Adress Adress{ get; set; }
public bool ShouldSerializeAdress()
{
return Adress!= null;
}
}
If you have a mapped class-to-Xml, you can use this 2 methods:
const string PrefixXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
public static object Deserialize<T>(T obj, string xmlText)
{
try
{
XmlSerializer deserializer = new XmlSerializer(typeof(T));
TextReader textReader = new StringReader(xmlText);
return (T)deserializer.Deserialize(textReader);
}
catch (Exception ex)
{
//Catch here.
return null;
}
}
public static XmlDocument Serialize<T>(T obj)
{
string xmlString = GerarXml.Gerar<T>(obj);
if (!xmlString.Contains("xml version="))
{
xmlString = PrefixXml + xmlString;
}
xmlString = xmlString.Replace(Environment.NewLine, string.Empty);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
return doc;
}
And if you want to get the XML as a string:
public static string GetXmlText(XmlDocument doc)
{
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
doc.WriteTo(xmlTextWriter);
string ret = stringWriter.ToString();
ret = ret.Replace(Environment.NewLine, string.Empty);
if (!ret.Contains("xml version="))
{
return PrefixXml + ret;
}
return ret;
}