使用LINQ to XML时,C#检查元素是否存在

Dav*_*her 9 c# xml linq linq-to-xml

好的,有点随机的问题,但最好的方法就是只需添加代码,你就能立刻看到我的意思:

XML:

<?xml version="1.0" encoding="utf-8" ?>
<customers>
  <customer>
    <id>1</id>
    <name>Blah-face</name>
    <Type>1</Type>
  </customer>
  <customer>
    <id>2</id>
    <name>Blah-face-2</name>
    <Type>2</Type>
  </customer>
  <customer>
    <id>3</id>
    <name>Blah-face-3</name>
    <Type>1</Type>
    <SuperType>1</SuperType>
  </customer>
</customers>
Run Code Online (Sandbox Code Playgroud)

C#:

XDocument linquee = XDocument.Load(path);

var superType = (from c in linquee.Descendants("customer")
                 where (c.Element("SuperType").Value == "1")
                 select c).ToList();
Run Code Online (Sandbox Code Playgroud)

这会产生一个空错误 - 我是否需要在它之前为每个客户添加"SuperType"元素并使用空值,或者是否有一个解决方法,这意味着我不必这样做?

干杯!

Jon*_*eet 13

试试这个:

var superType = (from c in from c in linquee.Descendants("customer")
                 where (string) c.Element("SuperType") == "1"
                 select c).ToList();
Run Code Online (Sandbox Code Playgroud)

基本上,如果你将空XElement引用转换为string,你将得到一个空引用(你可以与"1"进行比较).

如果元素丢失,则另一种方法是转换为int?(IIRC)将返回空int?值,但如果它存在但是非数字则会发出声响:

var superType = (from c in from c in linquee.Descendants("customer")
                 where (int?) c.Element("SuperType") == 1
                 select c).ToList();
Run Code Online (Sandbox Code Playgroud)


Ant*_*ram 6

您应该只需添加一个null检查

where c.Element("SuperType") != null 
&& [your other criteria]
Run Code Online (Sandbox Code Playgroud)