简体   繁体   中英

Reading all matches from attribute value XML C#

I have a code which retrieves only one value from the xml file using xmlreader.

<recordset>
    <itemidlist>
        <itemid idtype = "plant">787484545</itemid>
        <itemid idtype = "seed">659988222</itemid>
    </itemidlist>
    <itemidlist>
        <itemid idtype = "plant">90327328</itemid>
        <itemid idtype = "seed">099849999</itemid>
    </itemidlist>
    <itemidlist>
        <itemid idtype = "plant">34545488</itemid>
        <itemid idtype = "seed">787555444</itemid>
    </itemidlist>
</recordset>

And C# coded this entry:(s is the xml file)

using (var reader = XmlReader.Create(s))
{
    var nodecount = 0;
    var plant = "";
    var seed = "";
    var typeid = false;
    var typeid2 = false;
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element &&
            reader.Name == "recordset")
        {
            nodecount++;
        }

        if (reader.NodeType == XmlNodeType.Element &&
            reader.Name == "itemid")
        {
            var idtype = reader.GetAttribute("idtype");
            typeid = idtype == "plant";
            typeid2 = idtype == "seed";
        }
        while (typeid && reader.NodeType == XmlNodeType.Element &&
               reader.Name == "itemid")
        {
            plant = reader.ReadInnerXml();
        }
        while (typeid2 && reader.NodeType == XmlNodeType.Element &&
               reader.Name == "itemid")
        {
            seed = reader.ReadInnerXml();
        }
    }
}

and this happens when a add to datagridview:

Only one record was found: Plant Seed 787484545 659988222

You're only setting on seed and one plant variable, so if any more than one value is found it will be overwritten. How do you propose to return multiple values?

Any reason not to use LINQ to XML for this?

var doc = XDocument.Load(s);

var plants = doc.Descendants("itemid")
    .Where(x => (string) x.Attribute("idtype") == "plant")
    .Select(x => x.Value);

var seeds = doc.Descendants("itemid")
    .Where(x => (string) x.Attribute("idtype") == "seed")
    .Select(x => x.Value);

See this fiddle for a working demo.

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