简体   繁体   中英

How can I browse a specific level on a XML?

This is the XML that I have :

<ordinanze>
    <dataagg>17/10/2012 ore 16:30</dataagg>
    <ordinanza>
        <numero>02/2012</numero>
        <titolo>02/2012</titolo>
    </ordinanza>

    <ordinanza>
        <numero>02/2012</numero>
        <titolo>02/2012</titolo>
    </ordinanza>

    <ordinanza>
        <numero>02/2012</numero>
        <titolo>02/2012</titolo>
    </ordinanza>
</ordinanze>    

and I'd like to browse the first level with the attribute ordinanza (not the rest) So, 3 nodes in the foreach. How can I do it?

My code :

XmlNodeList StudentNodeList = myXmlDocument.SelectNodes("ordinanza");

foreach (XmlNode node in StudentNodeList)
{
    Response.Write(node.SelectSingleNode("//numero[1]").InnerText);
}

but it prints nothing!

How about using Linq To Xml

var xDoc = XDocument.Parse(xml); //or XDocument.Load(fileName)
var list =  xDoc.Descendants("ordinanza")
                .Select(n => new
                {
                    Numero = n.Element("numero").Value,
                    Titolo = n.Element("titolo").Value,
                })
                .ToList();

尝试使用XElement和Linq到XML

Your XPath is incorrect. Here is my favorite XPath Reference . To answer your question of how to get three nodes in the foreach try

var students = myXmlDocument.SelectNodes("/ordinanze/ordinanza");

However, I do suggest you dabble with some LINQ if you're not familiar with it yet.

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