Get TAG reference from daughter of an XML C #

2

XML:

<?xml version="1.0" encoding="UTF-8"?>
<clientes>
    <cliente>
        <nome>Cliente1</nome>
        <contatos>
            <contato>
                <nome>Contato1</nome>
            </contato>
            <contato>
                <nome>Contato2</nome>
            </contato>
        </contatos>
    </cliente>  
    <cliente>
        <nome>Cliente2</nome>
        <contatos>
            <contato>
                <nome>Contato3</nome>
            </contato>
            <contato>
                <nome>Contato4</nome>
            </contato>
        </contatos>
    </cliente>
</clientes>

I need to save in the database in two tables, the CLIENT and their CONTACTS, but I can only get each TAG at a time and they do not have reference like this:

           DataSet ds = new DataSet();
           ds.ReadXml(caminho);

           ds.Tables[0];
           //Aqui consigo obter os clientes
           ds.Tables[1];
           //Aqui consigo obter os contatos

That way I can not create the references, the keys on the side of the CLIENT x CONTACT relation.

    
asked by anonymous 02.09.2015 / 15:39

1 answer

2

This is, in my view, the worst way to read XML. Use XDocument instead:

XDocument document = XDocument.Load("clientes.xml");

var clientes = document.Root.Elements("cliente").ToList();
var primeiroCliente = clientes.First();
var contatosDoPrimeiroCliente = primeiroCliente.Elements("contatos").ToList();
var primeiroContato = contatosDoPrimeiroCliente.First();
var nomeDoPrimeiroContato = primeiroContato.Element("nome").Value;

XDocument implements Linq upon reading an XML. Then apply the extension methods as in the examples to obtain the desired values.

    
02.09.2015 / 16:33