Extract XML C#tags

Asked

Viewed 682 times

1

I was able to get a tag, but I couldn’t find a way to take a tag that repeats itself and store each repetition in a list.

XML example

<casa>
  <porta>
     <janela>Janela 1</janela>
     <janela>Janela 2</janela>
     <janela>Janela 2</janela>
  </porta>
</casa>

Current code of example:

 var retorno = (from nota in xmlRetorno.Elements()
                       where nota.Name.LocalName.Equals("porta")
                       select nota).ToList();

2 answers

2


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.

  • 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.

2

To get the XML elements you can use LINQ-to-XML, I made an example in a Console application using your XML and stayed like this:

    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;

    static void Main(string[] args)
    {            
        string xml = @"<casa>
                      <porta>
                         <janela>Janela 1</janela>
                         <janela>Janela 2</janela>
                         <janela>Janela 2</janela>
                      </porta>
                    </casa>";

        XDocument xDoc = XDocument.Parse(xml);
        var descendantsQuery = from desc in xDoc.Root.Descendants("janela")
                               select desc;

        foreach (var item in descendantsQuery)
        {
            Console.WriteLine(item.Value);
        }

        Console.ReadLine();
    }

On the line var descendantsQuery = from desc in xDoc.Root.Descendants("janela") we are informing that from the root element (xDoc.Root that in your XML is "port") we want to get descendants (xDoc.root.Descendants) whose name is "window".

  • would only exchange the line on which the result is obtained to obtain a list as it is placed. var descendantsQuery = from desc in xDoc.root.Descendants("window") select desc; ;List<string> descendantsQuery = new List<string>() from desc in xDoc.Root.Descendants("janela")&#xA; select desc;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.