0

我一直在玩 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.
我一直在关注本教程,并且在他们的屏幕上它可以工作,但在我的屏幕上却没有。

4

2 回答 2

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

应该

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

您正在查询错误的元素,该元素将返回一个值并在您使用它时null抛出一个值。NullPointerException.Value

于 2013-10-31T12:10:50.587 回答
1

线

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

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

于 2013-10-31T12:10:55.887 回答