简体   繁体   中英

c# same tag name on a xml element

i got this case, i get all the elements on a xmlnodelist using the function getelementesbytagname(""), but sometimes i can had something like this.

<?xml version="1.0" encoding="UTF-8" ?>
<Element xsi:schemaLocation="http://localhost/AML/CaseInvestigationMangement/Moduli/XmlImportControls/xsdBorrow.xsd xsd2009027_kor21.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<nodo>
    <nombre>nodo1</nombre>
    <dato>1</dato>
    <otronodo>
        <nombre>nododentrodenodo</nombre>
        <dato2>23</dato2>
    </otronodo>
</nodo>
<nodo>
    ...
</nodo>
</Element>

if y search all the nodes by the name "nombre" well i get the nodo nombre and the otronodo nombre.

can i get only the name of the nodo node?

I think you want only the nombre values that have a nodo parent, but it's possible you want any nombre from any child of Element . With XPath and SelectNodes , you can do either, so I've included both below. SelectNodes returns XmlNodeList , just like GetElementsByTagName() does.

var doc = new XmlDocument();

doc.LoadXml(@"<?xml version=""1.0"" encoding=""UTF-8"" ?>
<Element>
    <nodo>
        <nombre>nodo1</nombre>
        <dato>1</dato>
        <otronodo>
            <nombre>nododentrodenodo</nombre>
            <dato2>23</dato2>
        </otronodo>
    </nodo>
    <nodo>
        <nombre>nodo2</nombre>
    </nodo>
    <frodo>
        <nombre>frodo nodo</nombre>
    </frodo>
</Element>
");

//  Any nombre whose parent is a nodo
var nodosNombres = doc.DocumentElement.SelectNodes("//nodo/nombre");

//  Any nombre belonging to any child of Element
var topNombres = doc.DocumentElement.SelectNodes("/Element/*/nombre");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM