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/
When I write this linq query
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 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? 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.
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
.
You also need to use Attribute("ProgramName").value.Equals("EnviroEpi")
to get to the value of the program name attribute.
You want Descendants("Program")
instead:
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. You need to do null checks along the way, you can't really just chain a bunch of objects together like you've done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.