Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在xml文件中创建XElement之前,需要一种简单的方法来检查XElement是否存在_C#_Xml - Fatal编程技术网

C# 在xml文件中创建XElement之前,需要一种简单的方法来检查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

我需要检查xml文件中是否存在XElement。下面的代码抛出了一个异常,所以我还不知道如何解决它

 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,你会有更多的机会得到答案