[英]C# check an element exists while using 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>
C#:
XDocument linquee = XDocument.Load(path);
var superType = (from c in linquee.Descendants("customer")
where (c.Element("SuperType").Value == "1")
select c).ToList();
這會出現一個空錯誤 - 我是否需要在它之前為每個客戶添加“SuperType”元素並使用空值,或者是否有一個解決方法,這意味着我不必這樣做?
干杯!
試試這個:
var superType = (from c in from c in linquee.Descendants("customer")
where (string) c.Element("SuperType") == "1"
select c).ToList();
基本上,如果你將一個空的XElement
引用轉換為string
,你將得到一個空引用(你可以與“1”進行比較)。
另一種方法是轉換為int?
哪個(IIRC)將返回null int?
如果元素缺失則返回值,但如果它存在但是非數字則會發出聲響:
var superType = (from c in from c in linquee.Descendants("customer")
where (int?) c.Element("SuperType") == 1
select c).ToList();
您應該只需添加一個null檢查
where c.Element("SuperType") != null
&& [your other criteria]
在嘗試從中讀取值之前,您是否嘗試檢查SuperType
元素是否存在?
...
where (c.Element("SuperType") != null && c.Element("SuperType").Value == "1")
...
我找到了一個很好的解決方案,使用Any()結合條件運算符:
result = entry.Elements(ArbitraryElement).Any() ? (entry.Element(ArbitraryElement).Attributes(ArbitraryAttribute).Any() ? entry.Element(ArbitraryElement).Attribute(ArbitraryAttribute).Value : "-1") : "-1"
訣竅是使用Elements()和Any()來檢查元素是否存在(Attributes()相同)
所以對於這個例子,它將是這樣的:
var superType = from c in linquee.Descendants("customer")
select c.Elements("SuperType").Any() ? c.Element("SuperType").Value : "0";
我會這樣做:
var superType = linquee.Descendants("customer").
Where(c => c.Element("SuperType") != null
&& c.Element("SuperType").Value == "1");
也應該能夠用擴展來清理這種東西,比如...
public string Element_valStr(XElement xElm, string xName)
{
if (xElm.Element(xName) == null) return string.empty;
return xElm.Element(xName).Value;
}
然后只是:
var superType = (from c in linquee.Descendants("customer")
where (c.Element_valStr("SuperType") == "1")
select c).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.