检查XElement(记录)是否存在?

时间:2014-01-18 14:19:14

标签: c# linq linq-to-xml

如何检查XElement是否有记录& INVID属性? 我的函数只返回单个XElement。即,

<INVENTORY>
  <Record>
    <INVID>1315</INVID>
    <INVNAME>TEST LOCATIONTEST</INVNAME>
    <HOSPNAME>TEST LOCATION</HOSPNAME>
    <INVTYPE>CLINICAL</INVTYPE>
    <INVDT>2013-09-30T09:30:00</INVDT>
    <INVDEF>YES</INVDEF>
    <INVACT>YES</INVACT>
    <UPDDTTM />
    <UPDUSR />
    <ENBREF>true</ENBREF>
    <INVPWD>101315</INVPWD>
  </Record>
</INVENTORY>


XElement xInventory = GetDefaultInventory();        
bool hasInventory = xInventory.Elements("INVID").Any();  //What to do here ? 

if (hasInventory)
{  
    //TO DO Some action 
}

2 个答案:

答案 0 :(得分:9)

如果要检查inventory元素是否包含带有Record子元素的INVID元素,则可以使用XPath:

XElement inventory = GetDefaultInventory();
XElement invid = inventory.XPathSelectElement("Record/INVID");
if (invid == null) 
    // not exist

或LINQ方式:

bool exists = inventory.Elements("Record").Elements("INVID").Any();

答案 1 :(得分:0)

这个怎么样:

bool hasInventory = xInventory.Elements("Record").Any() && xInventory.Descendants("INVID").Any();

这将检查xInventory元素是否具有直接子Record,如果有,则检查xInventory是否包含子元素INVID