我有我的示例XML文件:
<?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>
和我的计划:
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 = (string) a.Attribute("lastName")
};
if (all == null)
Console.WriteLine("Null !");
else
foreach (contact t in all)
{
test = t.ToString();
Console.WriteLine(t.ToString());
}
}
Console.ReadKey();
}
}
此代码显示空白控制台窗口。没有“空虚!”没有接触元素。我花了很多时间思考为什么......有人能帮帮我吗?当我把断点放在foreach语句中时它不起作用
答案 0 :(得分:3)
实际上有几个原因。
Elements
仅为您提供文档的顶级元素(“contacts”元素),因此您应该使用Descendants
来获取较低级别的元素。这是工作代码:
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
};
答案 1 :(得分:2)
尝试使用Descendants()
代替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")
};
或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")
};