Get child tag reference from XML C#

Asked

Viewed 521 times

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 once and they have no reference thus:

           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’t create the references, the keys in the CLIENT x CONTACT.

1 answer

2


This is, in my view, the worst way to read an XML. Use Xdocument in place:

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 on top of reading an XML. Then just apply the extension methods as in the examples to get the desired values.

  • 1

    Using Linq I was navigating level by level of Xelement after creating Xdocument using a simple foreach

Browser other questions tagged

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