2011-11-29 115 views
1

我有一个XML结构:查询不获取所有记录

<pit> 
    <ROW TestID="47855" ExecutionID="1510034507" TestName="USHP" AssertionName="Check News" Status="1" TestLatencyMs="5448" Date="2011-11-29 01:43:45.117" HttpCode="" Error="" TestOwner="mdk" AssertionID="119117" /> 
    <ROW TestID="47855" ExecutionID="1510028579" TestName="USHP" AssertionName="Check News" Status="0" TestLatencyMs="7312" Date="2011-11-29 01:41:46.273" HttpCode="" Error="" TestOwner="fdxk" AssertionID="119117" /> 
    <ROW TestID="47855" ExecutionID="1510022153" TestName="USHP" AssertionName="Check News" Status="0" TestLatencyMs="5860" Date="2011-11-29 01:39:44.153" HttpCode="" Error="" TestOwner="klo" AssertionID="119117" /> 
    </pit> 

,我尝试使用此查询来获取我的ExecutionIDs但无济于事:(我不知道什么是错

List<int> executionIdList = new List<int>(); 
    try 
    { 
     executionIdList = (from result in xDoc.Root.Descendants("ROW") 
          where result != null && 
          result.Attribute("Status").Value.Equals("0", StringComparison.CurrentCultureIgnoreCase) 

          select result.Attributes("ExecutionID")).FirstOrDefault().Select(x => int.Parse(x.Value)).ToList(); 
    } 

我只得到与上述查询的第一个值。

回答

1

可以从的XDocument如下所示取YOUT ExecutionIds:

XDocument doc = XDocument.Load(@"C:\Sample1.xml"); 
List<string> ids = doc.Descendants("pit").Elements().Select(i => i.Attribute("ExecutionID").Value).ToList(); 

上面的代码加载从文件Sample1.xml的XML然后将所有executionIDs取成一个列表对象。如果需要检查状态值是否为“0”,则可以向查询添加更多条件。以下是条件代码

List<string> ids = doc.Descendants("pit").Elements().Where(k=>k.Attribute("Status").Value == "0").Select(i => i.Attribute("ExecutionID").Value).ToList(); 

希望有所帮助。

0

你得到第一行的元素,因为您的查询呼吁“行”元素的后代即

xDoc.Root.Descendants( “ROW”)

尝试通过用下面的代码替换此:

xDoc.Root.Descendants( “坑”)

这将返回所有元素,它们是元素的后代。

+0

nope this doesnt work..I get this object reference exception with this – Navyseal

+0

他可以选择“行”,它会返回所有“行”元素的集合。 “坑”会返回父元素,你必须事后不必要地迭代。 –

+0

我想我得到这个 executionIdList =(从结果xDoc.Root.Descendants( “行”) 其中结果!= NULL && result.Attribute( “状态”)。Value.Equals( “失败”,StringComparison .CurrentCultureIgnoreCase) select int.Parse(result.Attribute(“ExecutionID”)。Value))。ToList(); – Navyseal

1

,你没有得到结果的原因是因为

IEnumerable<int> executionIds; 

executionIds = 
    from result in xDoc.Root.Descendants("ROW").Attributes("ExecutionID") 
    select int.Parse(result.Value); 

是你所需要的东西。你的函数在选择部分包含了许多看似不必要的代码(但这是你要判断的),包括一个FirstorDefault语句,它只会选择第一条记录,或者如果没有记录存在,它将默认预定义的值。