从XPATH迁移到LINQ,需要帮助吗?

时间:2011-11-10 08:21:49

标签: c# xml linq xpath

我正在尝试更新应用程序中从XML文件读取数据的部分。目前我正在使用XPATH,但我想更新为LINQ。

对于简单的XPATH查询,我只需要获得1个值,没问题。但是下面的方法我无法弄清楚如何在这里使用LINQ。如果你能提出一些想法会很好。

    public ContinuityData GetSingleContinuityResult(string pin)
    {
        ContinuityData data;

        data = new ContinuityData();

        data.PinName = pin;

        data.PreVoltage = double.Parse(ztr.SelectSingleNode("/Document/Tests/Test[contains(Name, 'Pre Continuity')]/Groups/Group/Pins/Pin[Number='" + pin + "']/Spots/Spot/VIPair/Voltage").InnerText, CultureInfo.InvariantCulture);
        data.PreCurrent = double.Parse(ztr.SelectSingleNode("/Document/Tests/Test[contains(Name, 'Pre Continuity')]/Groups/Group/Pins/Pin[Number='" + pin + "']/Spots/Spot/VIPair/Current").InnerText, CultureInfo.InvariantCulture);

        data.PostVoltage = double.Parse(ztr.SelectSingleNode("/Document/Tests/Test[contains(Name, 'Post Continuity')]/Groups/Group/Pins/Pin[Number='" + pin + "']/Spots/Spot/VIPair/Voltage").InnerText, CultureInfo.InvariantCulture);
        data.PostCurrent = double.Parse(ztr.SelectSingleNode("/Document/Tests/Test[contains(Name, 'Post Continuity')]/Groups/Group/Pins/Pin[Number='" + pin + "']/Spots/Spot/VIPair/Current").InnerText, CultureInfo.InvariantCulture);

        return data;
    }

请注意,ztrXmlDocument个实例。

以下是XML文件的外观: enter image description here

1 个答案:

答案 0 :(得分:2)

试试这个

public ContinuityData GetSingleContinuityResult(string pin)
{
    ContinuityData data;

    data = new ContinuityData();

    data.PinName = pin;

    XElement xtr = XElement.Load("path/to/your/xml/file");

    Func<string, string, string, double> getViData =
        (testName, pin, mode) =>
        Convert.ToDouble(
            xtr 
                .Descendants("Test")
                .Where(test => test.Descendants("Name")
                                   .First().Value.Contains(testName))
                .Descendants("Pin")
                .Where(p => p.Descendants("Number")
                                .First().Value == pin)
                .Descendants("VIPair")
                .Descendants(mode)
                .First().Value);

    data.PreVoltage = getViData("Pre Continuity", pin, "Voltage");
    data.PreCurrent = getViData("Pre Continuity", pin, "Current");

    data.PostCurrent = getViData("Post Continuity", pin, "Current");
    data.PostVoltage = getViData("Post Continuity", pin, "Voltage");

    return data;
}

如果你理解这个问题,请不要犹豫!