LinqToXML Why this doesn't work?
I have my sample XML file:
<?xml version="1.0" encoding="utf-8" ?>
<contacts>
<contact contactId="2">
<firstName>Barney</firstName>
<lastName>Gottshall</lastName>
</contact>
<contact contactId="3">
<firstName>Armando</firstName>
<lastName>Valdes</lastName>
</contact>
<contact contactId="4">
<firstName>Adam</firstName>
<lastName>Gauwain</lastName>
</contact>
</contacts>
and my Program:
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
public class Program
{
public class contact
{
public int contactId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public override string ToString()
{
return firstName+" "+lastName;
}
}
public static void Main()
{
string test;
XDocument xDocument = XDocument.Load("items.xml");
var all = from a in xDocument.Elements("contact")
where a.Attribute("contactId")!=null
select new contact
{
contactId = (int) a.Attribute("contactId"),
firstName = (string) a.Attribute("firstName"),
lastName = (str开发者_如何学运维ing) a.Attribute("lastName")
};
if (all == null)
Console.WriteLine("Null !");
else
foreach (contact t in all)
{
test = t.ToString();
Console.WriteLine(t.ToString());
}
}
Console.ReadKey();
}
}
This code shows me blank console window. There's no "Null !" and no contact element. I spent a lot of time thinking why is that... could someone help me? when I put breakpoint inside foreach statement it's not working
There are actually a couple of reasons.
Elements
only gives you top-level elements of the document (the "contacts" element), so you should useDescendants
to get lower-level elements).- firstName and lastName are elements, not attributes.
Here's working code:
var all = from a in xDocument.Descendants("contact")
where a.Attribute("contactId")!=null
select new contact
{
contactId = (int) a.Attribute("contactId"),
firstName = (string) a.Element("firstName").Value,
lastName = (string) a.Element("lastName").Value
};
Try Descendants()
instead of Elements()
var all = from a in xDocument.Descendants("contact")
where a.Attribute("contactId") != null
select new contact
{
contactId = (int) a.Attribute("contactId"),
firstName = (string) a.Attribute("firstName"),
lastName = (string) a.Attribute("lastName")
};
or Element("contacts").Elements("contact")
var all = from a in xDocument.Element("contacts").Elements("contact")
where a.Attribute("contactId") != null
select new contact
{
contactId = (int) a.Attribute("contactId"),
firstName = (string) a.Attribute("firstName"),
lastName = (string) a.Attribute("lastName")
};
精彩评论