当相同的元素存在两次时,无法读取XML

时间:2015-03-03 15:32:29

标签: c# xml linq

示例文件:

<EMPLOYEES>
    <EMPLOYEE>
    <EMPID>110404</EMPID>
    <FIRST_NAME>JOHN</FIRST_NAME>
    <LAST_NAME>QARTAR</LAST_NAME>
    <JOIN_DATE>2014-12-17</JOIN_DATE>
    <DESIGNATION>
        <VALUE>OFFICER</VALUE>
        <VALUE>SENIOR OFFICER</VALUE>
    </DESIGNATION>
    <LAST_PROMOTION>
        <VALUE>2014-12-17</VALUE>
    </LAST_PROMOTION>
    </EMPLOYEE>
</EMPLOYEES>

我的代码:

var individuals =  
    from 
        Linq_tab in xmlDoc.Descendants("EMPLOYEE")
    select new objEMPLOYEE
    {
        EMPID = (string)Linq_tab.Element("EMPID"),
        FIRST_NAME = (string)Linq_tab.Element("FIRST_NAME"),
        LAST_NAME = (string)Linq_tab.Element("LAST_NAME"),
        JOIN_DATE = (string)Linq_tab.Element("JOIN_DATE"),
        DESIGNATION = new DESIGNATION_LIST()
        {
            VALUES_DESIGNATIONS = new List<DESIG>(from val in Linq_tab.Descendants("DESIGNATION")
                                     select new DESIG
                        {
                            VALUE = (string)val.Element("VALUE"),
                        })
        },
        LAST_PROMOTION = new LAST_PROMOTION_LIST()
        {
            VALUES_LAST_PROMOTION = new List<LAST_PROMOTION>(from val in Linq_tab.Descendants("LAST_PROMOTION")
                                     select new LAST_PROMOTION
                        {
                            VALUE = (string)val.Element("VALUE"),
                        })
        }
    };

一切都很好,但DESIGNATION。 只返回第一行。如何读取具有相同标签名称VALUE的两行名称?

1 个答案:

答案 0 :(得分:3)

您的XML中只有一个DESIGNATION元素 - 您真正您需要嵌套VALUE元素的列表:

VALUES_DESIGNATIONS = (from val in Linq_tab.Descendants("DESIGNATION").Elements("VALUE")
    select new DESIG
    {
        VALUE = val.Value,
    }).ToList();

也不要像这样大写变量 - 他们在尖叫我!

更具可读性:

VALUES_DESIGNATIONS =  Linq_tab.Descendants("DESIGNATION")
   .Elements("VALUE")
   .Select(x=> new Desig() {VALUE = x.Value })
   .ToList();