简体   繁体   English

从属性值XML C#读取所有匹配项

[英]Reading all matches from attribute value XML C#

I have a code which retrieves only one value from the xml file using xmlreader. 我有一个使用xmlreader从xml文件中仅检索一个值的代码。

<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) C#编码了该条目:(s是xml文件)

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: 当添加到datagridview时会发生这种情况:

Only one record was found: Plant Seed 787484545 659988222 仅找到一个记录:植物种子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. 您只需要设置seed和一个plant变量,因此,如果发现一个以上的值,它将被覆盖。 How do you propose to return multiple values? 您如何建议返回多个值?

Any reason not to use LINQ to XML for this? 有什么理由不为此使用LINQ to XML?

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. 请参阅此小提琴以获得有效的演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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