繁体   English   中英

在C#中使用LINQ查询数据

[英]Querying data using LINQ in C#

我一直在玩XDocument和LINQ。 我设法得到一个文件来写:

<SchoolData storeName="mikveIsrael" location="mikve">
    <employee>
        <personalInfo>
            <name>Ilan Berlinbluv</name>
            <zip>58505</zip>
        </personalInfo>
        <employeeInfo>
            <salary>5000</salary>
            <id>1</id>
        </employeeInfo>
    </employee>
    <employee>
        <personalInfo>
            <name>Noam Inbar</name>
            <zip>58504</zip>
        </personalInfo>
        <employeeInfo>
            <salary>4500</salary>
            <id>2</id>
        </employeeInfo>
    </employee>
</SchoolData>  

我一直在尝试使用以下代码读取值:

public void QueryDoc(XDocument doc)
{
    var data = (from item in doc.Descendants("employee")
               select new {
                   name = item.Element("personalInfo").Element("name").Value,
                   salary = item.Element("employeeInfo").Element("salary").Value,
                   ID = item.Element("employeeInfo").Element("ID").Value,
                   zip = item.Element("personalInfo").Element("zip").Value
                   });
        foreach (var p in data)
        {
            Console.WriteLine(p.ToString());
        }
    }

但是,当我尝试运行代码时,它给了我一个例外: Object reference not set to an instance of an object.
我一直在关注本教程 ,并且在他们的屏幕上可以使用,但是在我的屏幕上却不能。

ID = item.Element("personalInfo").Element("ID").Value,

应该

ID = item.Element("employeeInfo").Element("id").Value,

您正在查询错误的元素,当在元素上使用.Value时,该元素将返回null值并引发NullPointerException

线

ID = item.Element("personalInfo").Element("ID").Value,

将失败,因为在personalInfo不存在元素ID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM