LINQ to XML查询 - 代码只返回第一项

时间:2010-09-26 04:17:31

标签: linq-to-xml

我花了几个小时阅读和了解LINQ to XML,但我在这里遇到了障碍。以下是我的XML文件示例:

<project>
    <project_number>20071234</project_number>
    <project_name>ProjectA</project_name>
    <project_unc>\\fileserver1\projects\</project_unc>
    <contract>
        <full_name>Contract 00 Project1</full_name>
        <directory_name>00_Project1</directory_name>
    </contract>
    <contract>
        <full_name>Contract 01 Project2</full_name>
        <directory_name>01_Project2</directory_name>
    </contract>
</project>
<project>
    <project_number>20081234</project_number>
    <project_name>ProjectB</project_name>
    <project_unc>\\fileserver2\projects\</project_unc>
    <contract>
        <full_name>Contract 00 Project3</full_name>
        <directory_name>00_project3</directory_name>
    </contract>
    <contract>
        <full_name>Contract 01 Project4</full_name>
        <directory_name>01_project4</directory_name>
    </contract>
</project>

在我的程序中,有人会从下拉列表中选择一个project_number。当他们这样做时,它将触发对XML文件的查询,该文件将获取该project_number,并查找所有合同。

XDocument XDoc = null;
XDoc = XDocument.Load("projects.xml");
List<ProjectContract> pc = new List<ProjectContract>(); //Created in class
var query = from xml in XDoc.Descendants("project") where (string)xml.Element("project_number") == dropDown1.SelectedItem
             select new ProjectContract
             {
                 fullname = (string)xml.Element("contract").Element("full_name"),
                 dirname = (string)xml.Element("contract").Element("directory_name")
             };
pc = query.ToList();

我显然在这里做错了;我只是看不出来。此代码仅返回任一项目中的第一个合同项目,但不同时返回两者。

2 个答案:

答案 0 :(得分:1)

您需要获取项目元素的所有后代联系人,然后为每个联系人选择一个新的项目联系人。您可以按如下方式更改查询,它可以按预期工作:

        var query = from xml in XDoc.Descendants("project")
                    from contactxml in xml.Descendants("contract")
                    where (string)xml.Element("project_number") 
                                                  == dropDown1.SelectedItem
                    select new ProjectContract
                    {
                        fullname = (string)contactxml.Element("full_name"),
                        dirname = (string)contactxml.Element("directory_name")
                    };

(我会使用xml.Element("whatever").Value代替xml.Element("whatever")。只是看起来更好。)

答案 1 :(得分:0)

试试这个

var query = from contract in XDoc.Descendants("contract")
            where contract.Parent.Element("project_number").Value == dropDown1.SelectedItem
            select new ProjectContract
                     {
                         fullname = (string)xml.Element("contract").Element("full_name"),
                         dirname = (string)xml.Element("contract").Element("directory_name")
                     };