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

9

好的,这是一个有些随意的问题,但最好的解决方法就是添加代码,你可以立即看到我的意思:

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"元素,还是有一种解决方法可以避免这样做?

谢谢!

6个回答

13

试试这个:

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

如果你将一个空的XElement转换为string,你将得到一个空引用(可以与“1”进行比较)。

另一个选择是转换为int?,如果元素不存在,则返回一个空的int?值,但如果它存在但不是数字,则会抛出异常:

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

完美,比检查空值要简单得多。马上就会“打勾”了。 - David Archer

6

您只需要添加一个检查空值的条件即可。

where c.Element("SuperType") != null 
&& [your other criteria]

3

在尝试读取SuperType元素的值之前,您是否尝试检查该元素是否存在?

...
where (c.Element("SuperType") != null && c.Element("SuperType").Value == "1")
...

0

还应该能够通过扩展来清理这种东西,例如...

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();

0
我会这样做:
var superType = linquee.Descendants("customer").
    Where(c => c.Element("SuperType") != null 
        && c.Element("SuperType").Value == "1");

0

我发现使用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";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接