简体   繁体   中英

read xml file with multiple elements to a list in asp.net c#

Here is my xml file called wfXml.xml

<?xml version="1.0" encoding="utf-8" ?>
<webformname>
    <wbfrm>
        <wfname>WebForm1</wfname>
        <wfrm>WebForm1.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm2</wfname>
        <wfrm>WebForm2.aspx</wfrm>
    </wbfrm>        
    <wbfrm>
        <wfname>WebForm3</wfname>
        <wfrm>WebForm3.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm4</wfname>
        <wfrm>WebForm4.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm5</wfname>
        <wfrm>WebForm5.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm6</wfname>
        <wfrm>WebForm6.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm7</wfname>
        <wfrm>WebForm7.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm8</wfname>
        <wfrm>WebForm8.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm9</wfname>
        <wfrm>WebForm9.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm10</wfname>
        <wfrm>WebForm10.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm11</wfname>
        <wfrm>WebForm11.aspx</wfrm>
    </wbfrm>
    <wbfrm>
        <wfname>WebForm12</wfname>
        <wfrm>WebForm12.aspx</wfrm>
    </wbfrm>
</webformname>

And here is a code sample that I found which uses xmldoc and Linq except it only deals with one element. How can I implement this code for my xml file which contains 2 elements?

XDocument doc = XDocument.Parse(xml);

List<string> list = doc.Root.Elements("id")
                       .Select(element => element.Value)
                       .ToList();

I guess I'm being lazy. I came up with this routine which I could create my list from -- just seems a little verbose. Any suggestions for an improved way would be appreciated:

XDocument doc = XDocument.Load(path + "wfXml.xml");

var wfrms = from r in doc.Descendants("wbfrm")
                    select new
                    {
                        Wfname = r.Element("wfname").Value,
                        Wfrm = r.Element("wfrm").Value
                    };

foreach (var m in wfrms)
{    
    Response.Write(string.Format( "{0}, {1} <br />", m.Wfname, m.Wfrm));
}

Then I could populate my List --string, string -- or probably use wfrms as the datasource itself.

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