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

时间:2016-03-16 09:41:22

标签: c# xml attributes 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>

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();
        }
    }
}

当添加到datagridview时会发生这种情况:

只找到一条记录: 植物种子 787484545 659988222

1 个答案:

答案 0 :(得分:1)

您只设置seed和一个plant变量,因此如果找到任何多个值,它将被覆盖。您如何建议返回多个值?

有什么理由不为此使用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);

有关正常工作的演示,请参阅this fiddle