简体   繁体   English

了解使用linq解析xml

[英]understanding of using linq to parse xml

I just have some codes here to clarify my doubts on linq xml parsing. 我这里只有一些代码来澄清我对linq xml解析的怀疑。 I have the following: 我有以下几点:

...
{

            XDocument xmlDoc = XDocument.Load(@"C:\Build.xml");
            var abc = from example in xmlDoc.Descendants("target")
                      select (string)target.Attribute("if");
            ...
            foreach(string example in abc)
           {
            ...
           }

            ...
           }

Can i ask that if it is true that in the line select (string)target.Attribute("if") i am selecting a string from the xml file from the value of "if" as shown in the xml file below: 我可以问一下,是否确实要在行中select (string)target.Attribute("if")我要从xml文件中从“ if”的值中选择一个字符串,如以下xml文件所示:

<xml>
<target if="thevalue">
</target>
</xml>

then i have this line: foreach(string example in abc) 然后我有这行: foreach(string example in abc)

Is it true that for every selected string of the "value" of the "if" attribute, i am doing something in the foreach loop. 的确,对于“ if”属性的“ value”的每个选定字符串,我在foreach循环中正在执行某些操作。

Yes, this is correct. 是的,这是正确的。 The variable "example" in your foreach loop will contain the value of the "if" attribute. 您的foreach循环中的变量“ example”将包含“ if”属性的值。

  var abc = from target in xDocument.Descendants("target")
            select (string)target.Attribute("if");

  foreach (var example in abc)
  {
    Console.WriteLine(example);
  }

try the above code in a console application and you'll see the values in the console window. 在控制台应用程序中尝试上面的代码,您将在控制台窗口中看到这些值。 Or you could use Debug.WriteLine(example) in a different type of application 或者您可以在其他类型的应用程序中使用Debug.WriteLine(example)

This is a better linq query expression however 这是一个更好的linq查询表达式

  var abc = from target in xDocument.Descendants("target").Attributes("if")
            select target.Value;

or change your linq query expression to 或将您的linq查询表达式更改为

  var abc = from target in xDocument.Descendants("target")
            select target.Attribute("if").Value;

EDIT To help with your issue with the Debugger: I've moved my mouse over abc and I see the debugger pop up the information window as shown in the image below 编辑为了帮助您解决调试器问题:我将鼠标移到abc上,并且看到调试器弹出信息窗口,如下图所示。

在此处输入图片说明

This first images show the "Results View" has those green arrows. 第一个图像显示“结果视图”具有那些绿色箭头。 You need to click on those arrows before you can see the result (as the message next to them says) 您需要先单击这些箭头,然后才能看到结果(如旁边的消息所述)

The second image then shows you the results 然后第二张图片显示结果 在此处输入图片说明

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

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