简体   繁体   English

遍历XML的所有节点并解析存储在属性中的值

[英]Iterate over all nodes of XML and parse values stored in attribute

I am trying to iterate over all nodes of an xml file and parse values stored in the attributes of "product-id" of nodes called "product". 我正在尝试遍历xml文件的所有节点并解析存储在称为“产品”的节点的“产品ID”属性中的值。

My code looks like this. 我的代码如下所示。

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;

class ReadFileFromFolder
{
    public static void Main()
    {
        XDocument xdoc = XDocument.Load("catalog.xml");

        foreach (XElement element in xdoc.Descendants())
        {
            if(element.Name == "product")
            {
                Console.WriteLine(element.Attributes["product-id"].Value);;   
            }
        }
    }
}

The error I get 我得到的错误

projects/DotNetProjects/FilterProducts/FilterProducts/FilterProducts/ReadFileFromFolder.cs(35,35): Error CS0021: Cannot apply indexing with [] to an expression of type 'method group' (CS0021) (FilterProducts) projects / DotNetProjects / FilterProducts / FilterProducts / FilterProducts / ReadFileFromFolder.cs(35,35):错误CS0021:无法将带有[]的索引应用于“方法组”类型的表达式(CS0021)(FilterProducts)

Super new to c# so probably something silly I am doing. c#超级新手,所以我可能正在做一些愚蠢的事情。

Using Linq-to-Xml it can be as simple as: 使用Linq-to-Xml可以很简单:

XDocument xdoc = XDocument.Load("catalog.xml");
var productids = xdoc.Descendants("product").Select(p => p.Attribute("product-id").Value);

'method group' means object's type has at least one method with that name. “方法组”表示对象的类型至少具有一种使用该名称的方法。 Group is used in the term because a method name can be overloaded. 术语中使用组,因为方法名可以重载。 '[]' can only be used to index fields and properties. “ []”只能用于索引字段和属性。

ReadFileFromFolder.cs(35,35) means to go to line 35, column 35 for the best-effort location of the error. ReadFileFromFolder.cs(35,35)表示转到第35行第35列,以获取错误的尽力而为位置。 In many tools, double-clicking on the error message will take you there. 在许多工具中,双击错误消息将带您到那里。

The place you are using '[]' is with the Attributes identifier. 您正在使用“ []”的位置带有“属性”标识符。 If you look at the documentation (F1) or declaration (F12), you'll see it is, in fact, a method group with one signature (not overloaded). 如果您查看文档(F1)或声明(F12),您会发现它实际上是带有一个签名(未重载)的方法组。 So, call it with '()'. 因此,用“()”来称呼它。

Try accessing attributes with "(" . that is causing error. try below 尝试使用“(”。访问属性,这会导致错误。请尝试以下操作

class ReadFileFromFolder
    {
        public static void Main()
        {
            XDocument xdoc = XDocument.Load("catalog.xml");
            foreach (XElement element in xdoc.Descendants())
            {
                if(element.Name == "product"){
                    Console.WriteLine(element.Attributes("product-id").Value);;   
                }
            }
        }
    }

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

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