简体   繁体   English

为什么linq to xml无法识别我的XML文件中的属性?

[英]Why doesn't linq to xml recognize my the attributes in my XML file?

I'm brand new to LINQ to XML (comfortable with LINQ to sql) and learning my way around with this tutorial http://www.joe-stevens.com/2010/01/08/linq-to-xml-tutorial/ 我是LINQ to XML的新手(对LINQ to sql很满意),并通过本教程http://www.joe-stevens.com/2010/01/08/linq-to-xml-tutorial/学习了自己的方法

When I write this linq query 当我写这个linq查询时

Dim data As XDocument = XDocument.Load(xmlFileLocation)
Dim outputFileLoc = (From c In data.Descendants("Program") Where c.Attribute("ProgramName").Equals("EnviroEpi") Select c)

on this XML file: 在此XML文件上:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Programs>
   <Program ProgramName="EnviroEpi">
      <Type>csv</Type>
      <Location>test</Location>
   </Program>
   <Program ProgramName="Epi">
       <Type>HL7</Type>
       <Location>test</Location>
   </Program>
   <Program ProgramName="Lead">
      <Type>csv</Type>
      <Location>test</Location>
   </Program>
</Programs>

I get an error: 我收到一个错误:

Sequence contains no elements 序列不包含任何元素

Does this mean that LINQ can't see the ProgramName attribute of my program nodes? 这是否意味着LINQ无法看到我的程序节点的ProgramName属性? Or am I missing something else? 还是我想念其他东西? As far as I can tell, I'm doing everything exactly like in the tutorial. 据我所知,我所做的一切都与本教程完全相同。

Thanks again for the help. 再次感谢您的帮助。 I'm really just getting a feel for LINQ to XML. 我真的只是对LINQ to XML有所了解。

Edit 编辑

... where c.attribute("ProgramName").Equals("EnviroEpi") // returns no elements. 

This works: 这有效:

 c.attribute("ProgramName").value.equals("EnviroEpi") //added in .value to get it to work

You don't want Descendants("Programs").Descendants , that would return any descendant of the Programs elements - most of which are unrelated and don't have a ProgramName attribute, hence you get a NullReferenceException . 您不希望Descendants("Programs").Descendants ,该函数将返回Programs元素的任何后代 -大多数元素不相关且没有ProgramName属性,因此得到NullReferenceException

You also need to use Attribute("ProgramName").value.Equals("EnviroEpi") to get to the value of the program name attribute. 您还需要使用Attribute("ProgramName").value.Equals("EnviroEpi")来获取程序名称属性的值。

You want Descendants("Program") instead: 您需要Descendants("Program")代替:

 Dim outputFileLoc = (From c In data.Descendants("Program") Where c.Attribute("ProgramName").Equals("EnviroEpi") Select c).First

The issue is most likely that data.Descendants("Programs") or data.Descendants("Programs").Descendants is null. 问题很可能是data.Descendants("Programs")data.Descendants("Programs").Descendants为null。 You need to do null checks along the way, you can't really just chain a bunch of objects together like you've done. 您需要在此过程中执行空检查,您不能真的像完成操作一样将一堆对象链接在一起。

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

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