如何解析Xml没有序列化并存储每个节点的Xpath

时间:2015-03-25 08:34:48

标签: c# xml parsing

我有以下xml文件。我想在C#中没有Seri​​lization的情况下解析它。

<StudentList>
<StudentCount>5</StudentCount>
<Student>
    <Id>1</Id>
    <Name>Abc</Name>
</Student>
<Student>
    <Id>2</Id>
    <Name>Efg</Name>
</Student>
<Student>
    <Id>3</Id>
    <Name>Ghi</Name>
</Student>
<Student>
    <Id>4</Id>
    <Name>Jkl</Name>
</Student>
<Student>
    <Id>5</Id>
    <Name>Mno</Name>
</Student>
</StudentList>

我想将以上xml数据存储在Student of Class类

List<Student>

Class Student
{
    public int Id = 0;
    public string Name = "";
}

这里我还想要每个值节点的Xpath 对于Ex:

StudentList\StudentCount
StudentList\Student\Id
StudentList\Student\Name

请帮帮我 我如何实现这一点?

2 个答案:

答案 0 :(得分:1)

尝试使用LINQ解析.xml(检查LINQ to read XML以获取有关如何执行此操作的示例)。您应该能够从那里实现您的其他要求 - 如果您在编码时遇到问题,请自己尝试并寻求帮助:)

答案 1 :(得分:1)

快速解决方案让您入门:

创建一个XElement:

    XElement studentXml = XElement.Parse (
    @"<StudentList>
    <StudentCount>5</StudentCount>
    <Student>
        <Id>1</Id>
    <Name>Abc</Name>
    </Student>
    <Student>
        <Id>2</Id>
        <Name>Efg</Name>
    </Student>
    <Student>
        <Id>3</Id>
        <Name>Ghi</Name>
    </Student>
    <Student>
        <Id>4</Id>
    <Name>Jkl</Name>
    </Student>
    <Student>
        <Id>5</Id>
    <Name>Mno</Name>
    </Student>
    </StudentList>");

..并从中选择:

var students = 
    studentXml
        .Descendants()
        .Where(node => node.Name == "Student")
        .Select(node => 
                 new Student {
                   Id = int.Parse(node.Descendants()
                                      .First(item => item.Name == "Id")
                                      .Value), 
                   Name = node.Descendants()
                                      .First(item => item.Name == "Name")
                                      .Value
                 });