如果为空,c# XML到linq错误
本文关键字:linq 错误 XML 如果 | 更新日期: 2023-09-27 18:12:20
我有一个正在解析XML
文件的method
。
public static List<UpperLevelGPS> ParseXml(string Document)
{
List<UpperLevelGPS> result = new List<UpperLevelGPS>();
result.Clear();
doc = XDocument.Load(Document);
result = (from n in doc.Descendants("level")
select new UpperLevelGPS()
{
CurrentLevel = int.Parse(n.Attribute("CurrentLevel").Value),
TeleNodes = (from l in n.Element("UpperLevelGPSs").Elements("UpperLevelGPS")
select new TeleNodes()
{
id = (int)(l.Attribute("id")),
UpperLevelGPSMapID = (int)l.Attribute("UpperLevelGPSMapID"),
DestinationMapID = (int)l.Attribute("DestinationMapID"),
HostelID = (int)l.Attribute("HostelID"),
x = (float)l.Attribute("x"),
y = (float)l.Attribute("y"),
z = (float)l.Attribute("z")
}).ToList()
}).ToList();
return result;
}
节点UpperLevelGPSs
并不总是存在于我的XML
文件中,所以上面的query
失败了。我如何捕获和处理null
事件?
检查linq语句前是否有:
public static List<UpperLevelGPS> ParseXml(string Document)
{
List<UpperLevelGPS> result = new List<UpperLevelGPS>();
result.Clear();
doc = XDocument.Load(Document);
var upperLevelGPSs = n.Element("UpperLevelGPSs");
if (upperLevelGPSs.Count > 0)
{
result = (from n in doc.Descendants("level")
select new UpperLevelGPS()
{
CurrentLevel = int.Parse(n.Attribute("CurrentLevel").Value),
TeleNodes = (from l in upperLevelGPSs .Elements("UpperLevelGPS")
select new TeleNodes()
{
id = (int)(l.Attribute("id")),
UpperLevelGPSMapID = (int)l.Attribute("UpperLevelGPSMapID"),
DestinationMapID = (int)l.Attribute("DestinationMapID"),
HostelID = (int)l.Attribute("HostelID"),
x = (float)l.Attribute("x"),
y = (float)l.Attribute("y"),
z = (float)l.Attribute("z")
}).ToList()
}).ToList();
}
return result;
}
注意:我还没有测试过。
{
id = (int)(l.Attribute("id")),
UpperLevelGPSMapID = (int?)l.Attribute("UpperLevelGPSMapID"),
DestinationMapID = (int)l.Attribute("DestinationMapID"),
HostelID = (int)l.Attribute("HostelID"),
x = (float)l.Attribute("x"),
y = (float)l.Attribute("y"),
z = (float)l.Attribute("z")
}).ToList()
}).ToList();
(Int ?)