【问题标题】:How Parse Xml Without serialization and store each node Xpath如何在不序列化的情况下解析 Xml 并存储每个节点 Xpath
【发布时间】:2023-04-02 22:30:01
【问题描述】:

我有以下 xml 文件。我想在 C# 中解析它而不进行序列化。

<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数据存储在学生类列表中

List<Student>

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

这里我还想要每个值节点的 Xpath 例如:

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

请帮帮我 我如何做到这一点???

【问题讨论】:

    标签: c# xml parsing


    【解决方案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
                     });
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        • 2011-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多