C#检查,同时使用LINQ to XML存在一个元素 [英] C# check an element exists while using LINQ to XML
问题描述
OK,随机问题,但要做到这一点,只是添加代码的最佳方式的一点,你就可以明白我的意思直线距离:
XML:
< XML版本=1.0编码=UTF-8>?
<客户>
<客户>
< ID> 1 LT; / ID>
<名称>布拉赫面< /名称>
<类型> 1 LT; /型号>
< /客户>
<客户>
< ID> 2'; / ID>
<名称>布拉赫面-2'; /名称>
<类型> 2'; /型号>
< /客户>
<客户>
<&ID→3 LT; / ID>
<名称>布拉赫面-3'; /名称>
<类型> 1 LT; /型号>
<超> 1 LT; /超>
< /客户>
< /客户>
C#:
的XDocument linquee = XDocument.Load(路径);
VAR超=(从C中linquee.Descendants(客户)
,其中(c.Element(父)。价值==1)
选择C).ToList();
这来了一个空的错误 - 我需要的父元素添加到每个客户之前有一个空值,或者是有一种解决方法,这将意味着我没有做到这一点?
干杯!
< DIV CLASS =h2_lin>解决方案
试试这个:
VAR超=(从C中从C在linquee.Descendants(客户)
,其中(串)c.Element(父)==1
选择C).ToList();如果你投一个空的XElement
引用
基本上到字符串
,你会得到一个空引用(你可以用1相比较)。
这是另一种方法是强制转换为 INT?
这(IIRC)将返回一个空 INT?
值,如果该元素是失踪,只好一声如果它的存在,但非数字:
VAR超=(从C由C在linquee.Descendants( 客户)
,其中(INT)c.Element(父)== 1
选择C).ToList()?;
OK, bit of a random question, but the best way to do this is to just add the code, you'll be able to see what I mean straight away:
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>
C#:
XDocument linquee = XDocument.Load(path);
var superType = (from c in linquee.Descendants("customer")
where (c.Element("SuperType").Value == "1")
select c).ToList();
This comes up with a null error - would I need to add the "SuperType" element to each customer before it with a null value, or is there a workaround that would mean I don't have to do that?
Cheers!
Try this:
var superType = (from c in from c in linquee.Descendants("customer")
where (string) c.Element("SuperType") == "1"
select c).ToList();
Basically if you cast a null XElement
reference to string
, you'll get a null reference (which you can compare with "1").
An alternative would be to cast to int?
which (IIRC) will return a null int?
value if the element is missing, but go bang if it's present but non-numeric:
var superType = (from c in from c in linquee.Descendants("customer")
where (int?) c.Element("SuperType") == 1
select c).ToList();
这篇关于C#检查,同时使用LINQ to XML存在一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!