需要找到一个属性值
<?xml version="1.0" encoding="UTF-8"?>
<Pit>
<ROW ExecutionID="1366617710" Date="2011-11-09 00:04:04.303" AssertionName="Check for critical conditions" />
<ROW ExecutionID="1366619608" Date="2011-11-09 00:04:16.893" AssertionName="Check for critical conditions" />
</Pit>
我正在尝试根据某个executionID 检索日期值。
我尝试使用下面的查询,但出现“异常”。这很简单,但不知道为什么会失败。
异常消息是未将对象引用设置为对象的实例。
public static string GetRowError(XDocument xmlDoc, string executionID)
{
string resultType = string.Empty;
try
{
resultType = (from testResult in xmlDoc.Elements("Pit")
where
testResult != null &&
testResult.Attribute("ExecutionID").Value.Equals(executionID, StringComparison.CurrentCultureIgnoreCase) == true
select testResult.Attribute("Date").Value).FirstOrDefault();
}
catch (Exception ex)
{
resultType = ex.ToString();
}
return resultType;
}
<?xml version="1.0" encoding="UTF-8"?>
<Pit>
<ROW ExecutionID="1366617710" Date="2011-11-09 00:04:04.303" AssertionName="Check for critical conditions" />
<ROW ExecutionID="1366619608" Date="2011-11-09 00:04:16.893" AssertionName="Check for critical conditions" />
</Pit>
I am trying to retrieve the date value based on a certain executionID.
I tried using the below query, but I reach an "exception". It's fairly simple but dunno why it fails.
The exception message is Object reference not set to an instance of an object.
public static string GetRowError(XDocument xmlDoc, string executionID)
{
string resultType = string.Empty;
try
{
resultType = (from testResult in xmlDoc.Elements("Pit")
where
testResult != null &&
testResult.Attribute("ExecutionID").Value.Equals(executionID, StringComparison.CurrentCultureIgnoreCase) == true
select testResult.Attribute("Date").Value).FirstOrDefault();
}
catch (Exception ex)
{
resultType = ex.ToString();
}
return resultType;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了@Henk Holterman 的回答之外 - 只是一个改进:
我会像这样编写我的查询,因为它考虑了一个没有executionID 的元素,而且也不需要 == true 。等于返回 bool 那么你为什么将它与 true 进行比较呢?根本没有理由。
In addition to @Henk Holterman answer - just an improvement :
I would write my query like this because it accounts for an element without the executionID and also the == true is not needed. Equals returns bool so why are you comparing it with true? No reason at all.
将返回
元素,其余逻辑假设它们是|
元素。使用
xmlDoc.Elements("Pit").Elements()
或直接选择xmlDoc.Descendants("ROW")
。您的错误是由以下原因引起的:
will return the
<Pit>
elements, the rest off your logic assumes they are<ROW>
elements.Either use
xmlDoc.Elements("Pit").Elements()
or directly selectxmlDoc.Descendants("ROW")
.Your error is caused by: