C# 在xml文件中创建XElement之前,需要一种简单的方法来检查XElement是否存在
我需要检查xml文件中是否存在XElement。下面的代码抛出了一个异常,所以我还不知道如何解决它C# 在xml文件中创建XElement之前,需要一种简单的方法来检查XElement是否存在,c#,xml,C#,Xml,我需要检查xml文件中是否存在XElement。下面的代码抛出了一个异常,所以我还不知道如何解决它 XDocument doc1 = XDocument.Load(@filePath); XElement arrivalInstructions = doc1.Descendants("arrivalInstructions").First(); if (arrivalInstructions == null) { here I would put the code to creat
XDocument doc1 = XDocument.Load(@filePath);
XElement arrivalInstructions = doc1.Descendants("arrivalInstructions").First();
if (arrivalInstructions == null)
{ here I would put the code to create the XElement but it never gets here }
我也试过,但也没用
XElement xml = XElement.Load(@filePath);
XElement configuration = xml.Element("Root");
var xxx = configuration.Element("arrivalInstructions");
if (xxx == null)
{ here I would put the code to create the XElement but it never gets here }
使用
FirstOrDefault
而不是First
。如果没有项,它不会抛出异常,它只返回null。这是C代码吗?如果是的话,把它标记为C,你会有更多的机会得到答案