我有以下代码:
protected void Page_Load(object sender, EventArgs e)
{
XElement xml = XElement.Load(Server.MapPath("ArenasMembers.xml"));
var query = from p in xml.Descendants("members")
select new
{
Name = p.Element("name").Value,
Email = p.Attribute("email").Value
};
foreach (var member in query)
{
Response.Write("Employee: " + member.Name + " " + member.Email + "<br />");
}
}
使用Visual Studio中的悬停信息正在正确读取XNL文件,但是foreach没有输出任何记录。
XML:
<?xml version="1.0" encoding="utf-8" ?>
<members>
<member>
<arena>EAA Office</arena>
<memberid>1</memberid>
<name>Jane Doe</name>
<email>test@gmail.com</email>
</member>
<member>
<arena>EAA Office</arena>
<memberid>2</memberid>
<name>John Bull</name>
<email>jb@ehotmail.org</email>
</member>
<member>
<arena>O2 Arena</arena>
<memberid>3</memberid>
<name>John Doe</name>
<email>john.doe@o2arena.co.uk</email>
</member>
<member>
<arena>O2 Arena</arena>
<memberid>4</memberid>
<name>Bernard Cribbins</name>
<email>bernard@gmail.com</email>
</member>
<member>
<arena>Colourline Arena</arena>
<memberid>5</memberid>
<name>John Bon Jovi</name>
<email>jbj@gmail.com</email>
</member>
<member>
<arena>NIA</arena>
<memberid>6</memberid>
<name>Rhianna</name>
<email>skimpy@gmail.com</email>
</member>
</members>
你能看出出了什么问题吗?
答案 0 :(得分:3)
“成员”的遗嘱尝试“成员”......
Descendants
会在您的代码中返回给定Element
下的所有子元素,您使用members
和name
查询email
,这些元素无法正常工作。
示例代码:
var query = from p in xml.Descendants("member")
select new
{
Name = p.Element("name").Value,
Email = p.Element("email").Value
};
答案 1 :(得分:0)
将属性(“电子邮件”)更改为元素(“电子邮件”)对我来说很合适。经过测试,希望获得批准。
public void XMLTEst()
{
var xml = @"<?xml version='1.0' encoding='utf-8' ?>"
+ " <members>"
+ " <member>"
+ " <arena>EAA Office</arena> "
+ " <memberid>1</memberid> "
+ " <name>Jane Doe</name> "
+ " <email>test@gmail.com</email> "
+ " </member> "
+ " <member> "
+ " <arena>EAA Office</arena> "
+ " <memberid>2</memberid> "
+ " <name>Linda Bull</name> "
+ " <email>linda.bull@eaaoffice.org</email> "
+ " </member> "
+ " <member> "
+ " <arena>O2 Arena</arena> "
+ " <memberid>3</memberid> "
+ " <name>John Doe</name> "
+ " <email>john.doe@o2arena.co.uk</email> "
+ " </member> "
+ " <member> "
+ " <arena>O2 Arena</arena> "
+ " <memberid>4</memberid> "
+ " <name>Bernard Cribbins</name> "
+ " <email>bernard@gmail.com</email> "
+ " </member> "
+ " <member> "
+ " <arena>Colourline Arena</arena> "
+ " <memberid>5</memberid> "
+ " <name>John Bon Jovi</name> "
+ " <email>jbj@gmail.com</email> "
+ " </member> "
+ " <member> "
+ " <arena>NIA</arena> "
+ " <memberid>6</memberid>"
+ " <name>Rhianna</name>"
+ " <email>skimpy@gmail.com</email>"
+ " </member>"
+ "</members>";
XElement xmlFile = XElement.Parse(xml);
var query = from p in xmlFile.Descendants("member")
select new
{
Name = p.Element("name").Value,
Email = p.Element("email").Value
};
foreach (var member in query)
{
Response.Write("Employee: " + member.Name + " " + member.Email + "<br />");
}
}