使用ASP.NET mvc5从xml文件显示特定记录

时间:2018-10-03 15:26:44

标签: c# xml linq linq-to-xml innertext

我在找出问题所在时遇到问题。如果节点在上下文中不存在,这给我一个错误:

XmlDocument doc = new XmlDocument();
doc.Load("path");

Personal persons = doc.SelectNodes("/Persons/record")
 .Cast<XmlNode>()
 .Where(ID.Equals(node["ID"].InnerText) ==> This node does not exist
 .Select(node => new Personal()
 {
     ID = node["ID"].InnerText,
     Name = node["Name"].InnerText,
     Email = node["Email"].InnerText,
     DateOfBirth = node["DateOfBirth"].InnerText,
     Gender = node["Gender"].InnerText,
     City = node["City"].InnerText
 }).FirstOrDefault());

return View(persons);

XML:

<?xml version="1.0" encoding="UTF-8"?>
<Persons>
  <record>
    <ID>1602081497499</ID>
    <Name>Graham, Echo J.</Name>
    <Email>diam@Nullaeu.net</Email>
    <DateOfBirth>11/07/93</DateOfBirth>
    <Gender> Female</Gender>
    <City>Lloydminster</City>
  </record>
  <record>
    <ID>1688110330299</ID>
    <Name>Larson, Kevin K.</Name>
    <Email>eu.augue@penatibuset.co.uk</Email>
    <DateOfBirth>03/11/94</DateOfBirth>
    <Gender>Male </Gender>
    <City>Habra</City>
  </record>
</Persons>

我尝试将其更改为xmlNodecontains等。请,感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是一个使用Xml Linq的解决方案,它是比旧XmlElement新的Visual Studio库

?connection=CONNECTION_NAME