You can create a class containing the properties of your object and then use the class of Deserialize
where it will take the XML information and convert directly to your object. This way your code gets cleaner, and easy to maintain.
You can see examples from the community itself regarding this class in the links:
https://stackoverflow.com/questions/364253/how-to-deserialize-xml-document
https://stackoverflow.com/questions/3035637/xml-deserialization?rq=1
A generic deserialize code that I built just by demonstrating how it works:
XML Example:
<?xml version="1.0" encoding="ISO-8859-1"?>
<CLIENTE>
<ROW>
<TABELA>CLIENTE</TABELA>
<DATA_RECADASTRO/>
<ID_CLIENTE>10262202</ID_CLIENTE>
<ID_CLIENTE_RECADASTRO/>
<NOME_CLIENTE>CLIENTE EXEMPLO 1</NOME_CLIENTE>
<TIPO_CLIENTE>FIS</TIPO_CLIENTE>
</ROW>
<ROW>
<TABELA>CLIENTE</TABELA>
<DATA_RECADASTRO>20/03/2018</DATA_RECADASTRO>
<ID_CLIENTE>10450769</ID_CLIENTE>
<ID_CLIENTE_RECADASTRO/>
<NOME_CLIENTE>CLIENTE EXEMPLO 2</NOME_CLIENTE>
<TIPO_CLIENTE>FIS</TIPO_CLIENTE>
</ROW>
</CLIENTE>
public static T DeserializeObject<T>(string xml)
where T : class
{
if (string.IsNullOrEmpty(xml))
throw new InvalidOperationException("Empty XML ERROR");
using (var stringReader = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
}
Note that the object class you are passing to the method must contain the DataNotations
referring to each tag contained in the XML for Deserialize to do the conversion. Example:
[Serializable]
[XmlRoot(ElementName = "ROW")]
public class ClientInfo
{
[XmlElement(ElementName = "TABELA")]
public string NomeTabela { get; set; }
[XmlElement(ElementName = "ID_CLIENTE", Type = typeof(int))]
public int ClienteID { get; set; }
[XmlElement(ElementName = "ID_CLIENTE_RECADASTRO")]
public string ClientIDRecadastro { get; set; }
[XmlElement(ElementName = "NOME_CLIENTE")]
public string NomeCliente { get; set; }
[XmlElement(ElementName = "TIPO_CLIENTE")]
public string TipoCliente { get; set; }
[XmlIgnore]
public DateTime DataRecadastro { get; set; }
[XmlElement("DATA_RECADASTRO")]
public string SomeDateString
{
get { return this.DataRecadastro.ToString("dd-MM-yyyy"); }
set {
if (value != "")
this.DataRecadastro = DateTime.Parse(value);
}
}
}
To get the tags you need to deserialize? I did not understand, but if Raul marked as answer must have made sense in the context of it and then maybe I who did not understand the question rsrs.
– Renan
Exactly, to get the tags in an XML this class helps you to have access to each element and work directly with a class of properties.
– Victor Laio