好的,一个随机的问题,但最好的办法是添加代码,你可以看到我的意思是立即:
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();
基本上,如果你将一个null XElement引用转换为字符串,你将得到一个空引用(可以与“1”进行比较).
一个替代方法是转换为int?哪个(IIRC)将返回一个null int?如果元素丢失,则返回值,但是如果存在但不是数字,则为bang
var superType = (from c in from c in linquee.Descendants("customer") where (int?) c.Element("SuperType") == 1 select c).ToList();