简体   繁体   English

在解析xml“错误无序列元素”时检查元素是否存在

[英]Check if an elements exist while parsing xml “Error No Sequence element”

i have an xml with different set tags, i want to check if an element exist since i am having error no sequence element How do i check if tag szSerialNmbr is present, if not assign a null value or escape the Transaction Descendants. 我有一个带有不同set标记的xml,我想检查某个元素是否存在,因为我遇到了错误, 没有序列元素。如何检查标记szSerialNmbr是否存在,如果未分配空值或转义事务后代。 I went through other post but getting error Error "Extension method must be defined in a non-generic static class" 我经历了其他帖子,但收到错误错误“必须在非通用静态类中定义扩展方法”

XDocument xDocument = XDocument.Load(file);

foreach (var trans in xDocument.Descendants("Transaction"))
{
    var val1 = (string)trans.Descendants("Set").Elements("szSerialNmbr").First();

    var val2 = (string)trans.Descendants("Set").Elements("lMediaNmbr").First();

    var val3 = (string)trans.Descendants("Set").Elements("lMediaMember").First(); 
}

you can do a null check by adding a ? 您可以通过添加?进行空检查? , also if you are not sure if your set will contain the object you are looking for in linq, you can use firstOrDefault to allow null as a return value. ,如果还不确定集合中是否包含您要在linq中查找的对象,则可以使用firstOrDefault允许将null作为返回值。

var val1 = (string)trans?.Descendants("Set")?.Elements("szSerialNmbr")?.FirstOrDefault()?.Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM