需要找到一个属性值

本文关键字:一个 属性 | 更新日期: 2023-09-27 18:14:00

<?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检索日期值。

我尝试使用下面的查询,但我达到了一个"异常"。这是相当简单的,但不知道为什么它失败了。

异常消息为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;
}

需要找到一个属性值

xmlDoc.Elements("Pit")

将返回<Pit>元素,其余的逻辑假设它们是<ROW>元素。

选择xmlDoc.Elements("Pit").Elements()或直接选择xmlDoc.Descendants("ROW")

您的错误是由:

var attr = xmlDoc.Elements("Pit").Attribute("ExecutionID");  // attr = null
var id = attr.Value;  // error, attr == null

除了@Henk Holterman的回答-只是一个改进:

    var resultType = (from testResult in xmlDoc.Root.Descendants("ROW")
                  where testResult.Attribute("ExecutionID") != null && testResult.Attribute("ExecutionID").Value.Equals(executionID, StringComparison.CurrentCultureIgnoreCase)
                  select testResult.Attribute("Date").Value).FirstOrDefault();

我会这样写我的查询,因为它说明了一个没有executionID的元素,也不需要== true。等号返回bool,为什么要和true比较呢?没有理由。