解析大型XML提要并将信息拆分为多个模型

时间:2013-05-19 22:06:54

标签: c# xml entity-framework asp.net-mvc-4 xml-parsing

我有一个包含学生信息的大型XML Feed。

<students>
    <student>
        <studentId>10</studentId>
        <name>Joe Doe</name>
        <location>Main street</location>
        <studyId>1001</studyId>
        <study>Business 101</study>
    </student>
    <student>
        <studentId>255</studentId>
        <name>Max Friedman</name>
        <location>Main street</location>
        <studyId>223</studyId>
        <study>Computer Science</study>
    </student>
    <student>
        <studentId>452</studentId>
        <name>Josephine Smith</name>
        <location>Clinton Dr.</location>
        <studyId>881</studyId>
        <study>English Literature</study>
    </student>
    ... (2000 more rows)
</students>

我想将此信息存储在 3个单独的模型中,但我不想多次解析XML。

模特:

public class Student
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long StudentId { get; set; } // Use the Id from the feed
    public string Name { get; set; }
    public long StudyId { get; set; }
    [ForeignKey("StudyId")]
    public virtual Study Study { get; set; }
}

public class Study
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long StudyId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

public class Location
{
    public long LocationId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Study> Studies { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

我已尝试过不同的方法来做到这一点,但每次它最终都会变得凌乱,丑陋而且完全是spaghetticode。

在伪代码中,我执行了以下操作:

For each student in the XML
    Create a new Student object
    Check if the Location object already exists in the DB
    If not, create the Location object
    Add the Location object to the Student object
    etc... etc...
Persist the ICollection of Students to the db

如何以最少的代码完成我想要的工作?

0 个答案:

没有答案