首页 > 其他分享 >xml解析读取 linqtoxml

xml解析读取 linqtoxml

时间:2024-09-13 19:04:10浏览次数:10  
标签:xml linqtoxml Elements 读取 XElement Element student new string

XML解析读取

LINQtoXML\LINQtoXML\Program.cs

using System;
using System.Linq;
using System.Xml.Linq;

namespace LINQtoXML
{
    class Program
    {
        public void MethodSyntax()
        {
            var studentsXML = XElement.Load("Students.xml");

            var students = studentsXML
                .Elements("Student")
                .Select(student =>
                    student.Element("FirstName").Value + " " + student.Element("LastName").Value
                );

            foreach (var student in students)
            {
                Console.WriteLine(student);
            }
        }

        public void QuerySyntax()
        {
            var studentsXML = XElement.Load("Students.xml");

            var students =
                from student in studentsXML.Elements("Student")
                select student.Element("FirstName").Value + " " + student.Element("LastName").Value;

            foreach (var student in students)
            {
                Console.WriteLine(student);
            }
        }

        public void Test()
        {
            var studentsXML = XElement.Load("Students.xml");

            var students = studentsXML
                .Elements("Student")
                .Where(student => ((DateTime)student.Element("DateOfBirth")).Year == 2000)
                .Select(student =>
                    (string)student.Element("FirstName")
                    + " "
                    + (string)student.Element("LastName")
                    + " ("
                    + ((DateTime)student.Element("DateOfBirth")).ToShortDateString()
                    + ")"
                );
            foreach (var student in students)
            {
                System.Console.WriteLine(student);
            }
        }

        public void Test3()
        {

            var universityXML = XElement.Load("University.xml");
            var students = universityXML
                .Elements("Students")
                .Elements("Student")
                // .Where(student => (string)student.Attribute("ID") == "111")
                .Select(student => new
                {
                    Name = (string)student.Element("FirstName")
                        + " "
                        + (string)student.Element("LastName"),
                    Courses = student
                        .Elements("Courses")
                        .Elements("Course")
                        .Join(
                            universityXML.Elements("Courses").Elements("Course"),
                            studentCourse => (string)studentCourse.Attribute("ID"),
                            course => (string)course.Attribute("ID"),
                            (studentCourse, course) =>
                                new
                                {
                                    Id = (string)course.Attribute("ID"),
                                    Title = (string)course.Element("Title"),
                                    Grade = (decimal)studentCourse.Element("Grade"),
                                    Credits = (int)course.Element("Credits")
                                }
                        )
                });

            foreach(var student in students){
                System.Console.WriteLine(student.Name);
                System.Console.WriteLine(student.Courses.First().Title);
            }

        }


        static void Main(string[] args)
        {
            var program = new Program();
            Console.WriteLine("Method Syntax");
            program.MethodSyntax();
            System.Console.WriteLine("-------------------------");
            Console.WriteLine("Query Syntax");
            program.QuerySyntax();
            System.Console.WriteLine("-------------------------");
            program.Test();
            System.Console.WriteLine("-------------------------");
            program.Test3();
        }
    }
}




LINQtoXML\LINQtoXMLTests\AdvancedFunctionalityUnitTests.cs

using NUnit.Framework;
using System;
using System.Linq;
using System.Xml.Linq;
using LINQtoXML;

namespace LINQtoXMLUnitTests
{
    public class AdvancedFunctionalityUnitTests
    {
        XElement UniversityXML;

        [SetUp]
        public void Setup()
        {
            UniversityXML = XElement.Load("University.xml");
        }

        [Test]
        public void WhenJoiningTwoXMLTrees_ThenWeGetAnonymousObject()
        {
            var students = UniversityXML.Elements("Students").Elements("Student")
                .Where(student => (string)student.Attribute("ID") == "111")
                .Select(student => new
                {
                    Name = (string)student.Element("FirstName") + " " + (string)student.Element("LastName"),
                    Courses = student.Elements("Courses").Elements("Course")
                        .Join(UniversityXML.Elements("Courses").Elements("Course"),
                            studentCourse => (string)studentCourse.Attribute("ID"),
                            course => (string)course.Attribute("ID"),
                            (studentCourse, course) => new
                            {
                                Id = (string)course.Attribute("ID"),
                                Title = (string)course.Element("Title"),
                                Grade = (decimal)studentCourse.Element("Grade"),
                                Credits = (int)course.Element("Credits")
                            })
                });

            Assert.AreEqual("John Doe", students.ElementAt(0).Name);
            Assert.IsTrue(students.GetType().Name.Contains("WhereSelectEnumerableIterator"));
        }


        [Test]
        public void WhenJoiningTwoXMLTreesWithQuerySyntax_ThenWeGetAnonymousObject()
        {
            var students = 
                from student in UniversityXML.Elements("Students").Elements("Student")
                where (string)student.Attribute("ID") == "111"
                select new
                {
                    Name = (string)student.Element("FirstName") + " " + (string)student.Element("LastName"),
                    Courses =
                    (
                        from studentCourses in student.Elements("Courses").Elements("Course")
                        join course in UniversityXML.Elements("Courses").Elements("Course")
                        on (string)(studentCourses.Attribute("ID")) equals (string)course.Attribute("ID")
                        select new
                        {
                            Id = (string)course.Attribute("ID"),
                            Title = (string)course.Element("Title"),
                            Grade = (decimal)studentCourses.Element("Grade"),
                            Credits = (int)course.Element("Credits")
                        }
                    )
                };

            Assert.AreEqual("John Doe", students.ElementAt(0).Name);
            Assert.IsTrue(students.GetType().Name.Contains("WhereSelectEnumerableIterator"));
        }

        [Test]
        public void WhenJoiningTwoXMLTrees_ThenWeGetStudentClass()
        {
            var students = UniversityXML.Elements("Students").Elements("Student")
                .Where(student => (string)student.Attribute("ID") == "111")
                .Select(student => new Student()
                {
                    Name = (string)student.Element("FirstName") + " " + (string)student.Element("LastName"),
                    Courses = student.Elements("Courses").Elements("Course")
                        .Join(UniversityXML.Elements("Courses").Elements("Course"),
                            studentCourse => (string)studentCourse.Attribute("ID"),
                            course => (string)course.Attribute("ID"),
                            (studentCourse, course) => new Course()
                            {
                                Id = (string)course.Attribute("ID"),
                                Title = (string)course.Element("Title"),
                                Grade = (decimal)studentCourse.Element("Grade"),
                                Credits = (int)course.Element("Credits")
                            })
                });

            Assert.AreEqual("John Doe", students.ElementAt(0).Name);
            Assert.AreEqual("Student", students.ElementAt(0).GetType().Name);
        }

        [Test]
        public void WhenJoiningTwoXMLTrees_ThenWeGetXElementObject()
        {
            var newElement = 
                new XElement("Students",
                    UniversityXML.Elements("Students").Elements("Student")
                        .Where(student => (string)student.Attribute("ID") == "111")
                        .Select(student => new XElement("Student",
                            new XElement("Name", (string)student.Element("FirstName") + " " + (string)student.Element("LastName")),
                            new XElement("Courses", student.Elements("Courses").Elements("Course")
                                .Join(UniversityXML.Elements("Courses").Elements("Course"),
                                        studentCourse => (string)studentCourse.Attribute("ID"),
                                        course => (string)course.Attribute("ID"),
                                        (studentCourse, course) => new XElement("Course",
                                            new XAttribute("ID", (string)course.Attribute("ID")),
                                            new XElement("Title", (string)course.Element("Title")),
                                            new XElement("Grade", (decimal)studentCourse.Element("Grade")),
                                            new XElement("Credits", (int)course.Element("Credits"))
                                        )
                                )
                            )
                        ))
                    );

            Assert.AreEqual("XElement", newElement.GetType().Name);
            Assert.AreEqual(1, newElement.Elements("Student").Count());
            Assert.AreEqual("John Doe", newElement.Elements("Student").ElementAt(0).Element("Name").Value);
        }

        [Test]
        public void WhenJoiningTwoXMLTrees_ThenWeGetSumAndCount()
        {
            var students = UniversityXML.Elements("Students").Elements("Student")
                .Select(student => new
                {
                    Name = (string)student.Element("FirstName") + " " + (string)student.Element("LastName"),
                    TotalCredits = student.Elements("Courses").Elements("Course")
                        .Join(UniversityXML.Elements("Courses").Elements("Course"),
                            studentCourse => (string)studentCourse.Attribute("ID"),
                            course => (string)course.Attribute("ID"),
                            (studentCourse, course) => (int)course.Element("Credits")
                        )
                        .Sum(),
                    CoursesCount = student.Elements("Courses").Elements("Course")
                        .Join(UniversityXML.Elements("Courses").Elements("Course"),
                            studentCourse => (string)studentCourse.Attribute("ID"),
                            course => (string)course.Attribute("ID"),
                            (studentCourse, course) => (string)course.Attribute("ID")
                        )
                        .Count()
                });

            Assert.AreEqual(3, students.Count());
            Assert.AreEqual("John Doe", students.ElementAt(0).Name);
            Assert.AreEqual(9, students.ElementAt(0).TotalCredits);
            Assert.AreEqual(2, students.ElementAt(0).CoursesCount);
            Assert.IsTrue(students.GetType().Name.Contains("SelectEnumerableIterator"));
        }

        [Test]
        public void WhenGroupingResults_ThenWeGetStudentsBySemester()
        {
            var students = 
                new XElement("Semesters",
                    UniversityXML.Elements("Students").Elements("Student")
                        .GroupBy(student => (int)student.Element("Semester"))
                        .Select(group => new XElement("Semester",
                            new XAttribute("ID", (int)group.Key),
                            group.Select(s =>
                                new XElement("Student",
                                    new XElement("FirstName", (string)s.Element("FirstName")),
                                    new XElement("LastName", (string)s.Element("LastName"))
                                )
                            )
                        )));

            Assert.AreEqual(2, students.Elements("Semester").Count());
            Assert.AreEqual("1", students.Elements("Semester").ElementAt(0).Attribute("ID").Value);
            Assert.AreEqual("2", students.Elements("Semester").ElementAt(1).Attribute("ID").Value);
        }
    }
}

LINQtoXML\LINQtoXMLTests\SimpleFunctionalityUnitTests.cs

using NUnit.Framework;
using System;
using System.Linq;
using System.Xml.Linq;

namespace LINQtoXMLUnitTests
{
    public class SimpleFunctionalityUnitTests
    {
        XElement StudentsXML;

        [SetUp]
        public void Setup()
        {
            System.Console.WriteLine("this set up config");
            StudentsXML = XElement.Load("./Students.xml");
        }


        [Test]
        public void WhenUsingQuerySyntax_ThenWeGetAllStudents()
        {
            var students = 
                from student in StudentsXML.Elements("Student")
                select student.Element("FirstName").Value + " " + student.Element("LastName").Value;

            var expected = new string[] { "John Doe", "Jane Doe", "Jim Doe" };
            CollectionAssert.AreEqual(expected, students.ToArray());
        }

        [Test]
        public void WhenUsingMethodSyntax_ThenWeGetAllStudents()
        {
            var students = StudentsXML.Elements("Student")
                .Select(student => student.Element("FirstName").Value + " " + student.Element("LastName").Value);

            var expected = new string[] { "John Doe", "Jane Doe", "Jim Doe" };
            CollectionAssert.AreEqual(expected, students.ToArray());
        }


        [Test]
        public void WhenCastingElementsToString_ThenWeGetAllStudents()
        {
            var students = StudentsXML.Elements("Student")
                .Select(student => (string)student.Element("FirstName") + " " + (string)student.Element("LastName"));

            var expected = new string[] { "John Doe", "Jane Doe", "Jim Doe" };
            CollectionAssert.AreEqual(expected, students.ToArray());
        }

        [Test]
        public void WhenFilteringForDate_ThenWeGetStudentsFrom2000()
        {
            var students = StudentsXML.Elements("Student")
                .Where(student => ((DateTime)student.Element("DateOfBirth")).Year == 2000)
                .Select(student => (string)student.Element("FirstName")
                    + " " + (string)student.Element("LastName")
                    + " (" + ((DateTime)student.Element("DateOfBirth")).ToShortDateString() + ")");

            Assert.AreEqual(2, students.Count());
            Assert.IsTrue(students.ElementAt(0).StartsWith("John Doe"));
            Assert.IsTrue(students.ElementAt(1).StartsWith("Jim Doe"));
        }


        [Test]
        public void WhenFilteringForId_ThenWeGetStudentWithId222()
        {
            var student = StudentsXML.Elements("Student")
                .Where(student => (int)student.Attribute("ID") == 222)
                .FirstOrDefault();

            Assert.AreEqual(student.Attribute("ID").Value, "222");
        }

        [Test]
        public void WhenFilteringForClassId_ThenWeGetTwoStudents()
        {
            var students = StudentsXML.Elements("Student")
                .Where(student => student.Elements("Courses").Elements("Course")
                    .Any(course => (string)course.Attribute("ID") == "CS103"));

            Assert.AreEqual(2, students.Count());
            Assert.AreEqual("111", students.ElementAt(0).Attribute("ID").Value);
            Assert.AreEqual("333", students.ElementAt(1).Attribute("ID").Value);
        }

        [Test]
        public void WhenUpdatingStudentName_ThenWeGetCorrectStudent()
        {
            var student = StudentsXML.Elements("Student")
                .Where(student => (int)student.Attribute("ID") == 333)
                .FirstOrDefault();

            // student.Element("FirstName").Value = "Jimmy";

            Assert.AreEqual(student.Attribute("ID").Value, "333");
            Assert.AreEqual(student.Element("FirstName").Value, "Jim");
            // Assert.AreEqual(student.Element("FirstName").Value, "Jimmy");
        }


        [Test]
        public void WhenUpdatingMajor_ThenWeGetUpdatedStudent()
        {
            var students = StudentsXML.Elements("Student")
                .Where(student => (int)student.Element("Semester") == 2
                    && (string)student.Element("Major") == "Computer Science");

            foreach (var student in students)
            {
                student.Element("Courses").Add(new XElement("Course", new XAttribute("ID", "CS204"), new XElement("Grade")));
            }


            Assert.AreEqual("111", students.ElementAt(0).Attribute("ID").Value);
            Assert.AreEqual(3, students.ElementAt(0).Element("Courses").Elements("Course").Count());
            Assert.AreEqual("333", students.ElementAt(1).Attribute("ID").Value);
            Assert.AreEqual(3, students.ElementAt(1).Element("Courses").Elements("Course").Count());
        }

        [Test]
        public void WhenDeletingStudent_ThenWeGetCorrectRemainingStudent()
        {
            StudentsXML.Elements("Student")
                .Where(student => (int)student.Attribute("ID") == 333)
                .Remove();

            var students = StudentsXML.Elements("Student");

            Assert.AreEqual("111", students.ElementAt(0).Attribute("ID").Value);
            Assert.AreEqual("222", students.ElementAt(1).Attribute("ID").Value);
        }

        [Test]
        public void WhenCreatingNewStudent_ThenWeGetOneStudent()
        {
            XElement students =
                new XElement("Students",
                    new XElement("Student",
                        new XAttribute("ID", "111"),
                        new XElement("FirstName", "John"),
                        new XElement("LastName", "Doe"),
                        new XElement("DateOfBirth", "2000-10-2"),
                        new XElement("Semester", "2"),
                        new XElement("Major", "Computer Science"),
                        new XElement("Courses",
                            new XElement("Course",
                                new XAttribute("ID", "CS103"),
                                new XElement("Grade", "7.3")
                            ),
                            new XElement("Course",
                                new XAttribute("ID", "CS202"),
                                new XElement("Grade", "6.9")
                            )
                        )
                    )
                );

            Assert.AreEqual(1, students.Elements("Student").Count());
        }

        [Test]
        public void WhenCreatingNewStudentWithDefaultNamespace_ThenWeGetOneStudent()
        {
            XNamespace st = "http://www.testuni.edu/def";
            XElement students =
                new XElement(st + "Students",
                    new XElement(st + "Student",
                        new XAttribute("ID", "111"),
                        new XElement(st + "FirstName", "John"),
                        new XElement(st + "LastName", "Doe"),
                        new XElement(st + "DateOfBirth", "2000-10-2"),
                        new XElement(st + "Semester", "2"),
                        new XElement(st + "Major", "Computer Science"),
                        new XElement(st + "Courses",
                            new XElement(st + "Course",
                                new XAttribute("ID", "CS103"),
                                new XElement(st + "Grade", "7.3")
                            ),
                            new XElement(st + "Course",
                                new XAttribute("ID", "CS202"),
                                new XElement(st + "Grade", "6.9")
                            )
                        )
                    )
                );

            Assert.AreEqual(1, students.Elements(st + "Student").Count());
        }

        [Test]
        public void WhenCreatingNewStudentWithPrefixedNamespace_ThenWeGetOneStudent()
        {
            XNamespace st = "http://www.testuni.edu/def";
            XElement students =
                new XElement(st + "Students",
                    new XAttribute(XNamespace.Xmlns + "st", "http://www.testuni.edu/def"),
                    new XElement(st + "Student",
                        new XAttribute("ID", "111"),
                        new XElement(st + "FirstName", "John"),
                        new XElement(st + "LastName", "Doe"),
                        new XElement(st + "DateOfBirth", "2000-10-2"),
                        new XElement(st + "Semester", "2"),
                        new XElement(st + "Major", "Computer Science"),
                        new XElement(st + "Courses",
                            new XElement(st + "Course",
                                new XAttribute("ID", "CS103"),
                                new XElement(st + "Grade", "7.3")
                            ),
                            new XElement(st + "Course",
                                new XAttribute("ID", "CS202"),
                                new XElement(st + "Grade", "6.9")
                            )
                        )
                    )
                );

            Assert.AreEqual(1, students.Elements(st + "Student").Count());
        }
    }
}


LINQtoXML\run.bat

cd linqtoxml
dotnet run

LINQtoXML\LINQtoXMLTests\University.xml

<?xml version="1.0" encoding="utf-8" ?>
<University>
  <Students>
    <Student ID="111">
      <FirstName>John</FirstName>
      <LastName>Doe</LastName>
      <DateOfBirth>2000-10-2</DateOfBirth>
      <Semester>1</Semester>
      <Major>Computer Science</Major>
      <Courses>
        <Course ID="CS101">
          <Grade>7.3</Grade>
        </Course>
        <Course ID="CS102">
          <Grade>6.9</Grade>
        </Course>
      </Courses>
    </Student>
    <Student ID="222">
      <FirstName>Jane</FirstName>
      <LastName>Doe</LastName>
      <DateOfBirth>2001-2-22</DateOfBirth>
      <Semester>1</Semester>
      <Major>Electrical Engineering</Major>
      <Courses>
        <Course ID="EE101">
          <Grade>5.6</Grade>
        </Course>
        <Course ID="EE102">
          <Grade>8.8</Grade>
        </Course>
      </Courses>
    </Student>
    <Student ID="333">
      <FirstName>Jim</FirstName>
      <LastName>Doe</LastName>
      <DateOfBirth>2000-3-12</DateOfBirth>
      <Semester>2</Semester>
      <Major>Computer Science</Major>
      <Courses>
        <Course ID="CS102">
          <Grade>7.6</Grade>
        </Course>
        <Course ID="CS103">
          <Grade>8.2</Grade>
        </Course>
      </Courses>
    </Student>
  </Students>
  <Courses>
    <Course ID="CS101">
      <Title>Intro to programming</Title>
      <Credits>5</Credits>
    </Course>
    <Course ID="CS102">
      <Title>Discrete Mathematics</Title>
      <Credits>4</Credits>
    </Course>
    <Course ID="CS103">
      <Title>Data structures</Title>
      <Credits>6</Credits>
    </Course>
    <Course ID="EE101">
      <Title>Electromagnetism</Title>
      <Credits>5</Credits>
    </Course>
    <Course ID="EE102">
      <Title>Electronics</Title>
      <Credits>6</Credits>
    </Course>
  </Courses>
</University>

LINQtoXML\LINQtoXMLTests\Students.xml

<?xml version="1.0" encoding="utf-8" ?>
<Students>
  <Student ID="111">
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <DateOfBirth>2000-10-2</DateOfBirth>
    <Semester>2</Semester>
    <Major>Computer Science</Major>
    <Courses>
      <Course ID="CS103">
        <Grade>7.3</Grade>
      </Course>
      <Course ID="CS202">
        <Grade>6.9</Grade>
      </Course>
    </Courses>
  </Student>
  <Student ID="222">
    <FirstName>Jane</FirstName>
    <LastName>Doe</LastName>
    <DateOfBirth>2001-2-22</DateOfBirth>
    <Semester>1</Semester>
    <Major>Electrical Engineering</Major>
    <Courses>
      <Course ID="EE111">
        <Grade>5.6</Grade>
      </Course>
      <Course ID="EE303">
        <Grade>8.8</Grade>
      </Course>
    </Courses>
  </Student>
  <Student ID="333">
    <FirstName>Jim</FirstName>
    <LastName>Doe</LastName>
    <DateOfBirth>2000-3-12</DateOfBirth>
    <Semester>2</Semester>
    <Major>Computer Science</Major>
    <Courses>
      <Course ID="CS103">
        <Grade>7.6</Grade>
      </Course>
      <Course ID="CS202">
        <Grade>8.2</Grade>
      </Course>
    </Courses>
  </Student>
</Students>

LINQtoXML\LINQtoXMLTests\LINQtoXMLTests.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
    <PackageReference Include="NUnit" Version="3.13.1" />
    <PackageReference Include="NUnit3TestAdapter" Version="3.17.0" />
    <PackageReference Include="coverlet.collector" Version="3.0.2" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\LINQtoXML\LINQtoXML.csproj" />
  </ItemGroup>

  <ItemGroup>
    <None Update="Students.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="University.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

LINQtoXML\LINQtoXML\University.xml

<?xml version="1.0" encoding="utf-8" ?>
<University>
  <Students>
    <Student ID="111">
      <FirstName>John</FirstName>
      <LastName>Doe</LastName>
      <DateOfBirth>2000-10-2</DateOfBirth>
      <Semester>1</Semester>
      <Major>Computer Science</Major>
      <Courses>
        <Course ID="CS101">
          <Grade>7.3</Grade>
        </Course>
        <Course ID="CS102">
          <Grade>6.9</Grade>
        </Course>
      </Courses>
    </Student>
    <Student ID="222">
      <FirstName>Jane</FirstName>
      <LastName>Doe</LastName>
      <DateOfBirth>2001-2-22</DateOfBirth>
      <Semester>1</Semester>
      <Major>Electrical Engineering</Major>
      <Courses>
        <Course ID="EE101">
          <Grade>5.6</Grade>
        </Course>
        <Course ID="EE102">
          <Grade>8.8</Grade>
        </Course>
      </Courses>
    </Student>
    <Student ID="333">
      <FirstName>Jim</FirstName>
      <LastName>Doe</LastName>
      <DateOfBirth>2000-3-12</DateOfBirth>
      <Semester>2</Semester>
      <Major>Computer Science</Major>
      <Courses>
        <Course ID="CS102">
          <Grade>7.6</Grade>
        </Course>
        <Course ID="CS103">
          <Grade>8.2</Grade>
        </Course>
      </Courses>
    </Student>
  </Students>
  <Courses>
    <Course ID="CS101">
      <Title>Intro to programming</Title>
      <Credits>5</Credits>
    </Course>
    <Course ID="CS102">
      <Title>Discrete Mathematics</Title>
      <Credits>4</Credits>
    </Course>
    <Course ID="CS103">
      <Title>Data structures</Title>
      <Credits>6</Credits>
    </Course>
    <Course ID="EE101">
      <Title>Electromagnetism</Title>
      <Credits>5</Credits>
    </Course>
    <Course ID="EE102">
      <Title>Electronics</Title>
      <Credits>6</Credits>
    </Course>
  </Courses>
</University>

LINQtoXML\LINQtoXML\Students.xml

<?xml version="1.0" encoding="utf-8" ?>
<Students>
  <Student ID="111">
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
    <DateOfBirth>2000-10-2</DateOfBirth>
    <Semester>2</Semester>
    <Major>Computer Science</Major>
    <Courses>
      <Course ID="CS103">
        <Grade>7.3</Grade>
      </Course>
      <Course ID="CS202">
        <Grade>6.9</Grade>
      </Course>
    </Courses>
  </Student>
  <Student ID="222">
    <FirstName>Jane</FirstName>
    <LastName>Doe</LastName>
    <DateOfBirth>2001-2-22</DateOfBirth>
    <Semester>1</Semester>
    <Major>Electrical Engineering</Major>
    <Courses>
      <Course ID="EE111">
        <Grade>5.6</Grade>
      </Course>
      <Course ID="EE303">
        <Grade>8.8</Grade>
      </Course>
    </Courses>
  </Student>
  <Student ID="333">
    <FirstName>Jim</FirstName>
    <LastName>Doe</LastName>
    <DateOfBirth>2000-3-12</DateOfBirth>
    <Semester>2</Semester>
    <Major>Computer Science</Major>
    <Courses>
      <Course ID="CS103">
        <Grade>7.6</Grade>
      </Course>
      <Course ID="CS202">
        <Grade>8.2</Grade>
      </Course>
    </Courses>
  </Student>
</Students>

LINQtoXML\LINQtoXML\Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LINQtoXML
{
    public class Student
    {
        public string Name { get; set; }
        public IEnumerable<Course> Courses { get; set; }
    }

    public class Course
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public decimal Grade { get; set; }
        public int Credits { get; set; }
    }
}

LINQtoXML\LINQtoXML\LINQtoXML.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <None Update="Students.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

LINQtoXML\LINQtoXML.sln


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31911.196
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LINQtoXML", "LINQtoXML\LINQtoXML.csproj", "{FB9D1617-AC45-4CF9-B66B-FE3E53C0E992}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LINQtoXMLTests", "LINQtoXMLTests\LINQtoXMLTests.csproj", "{A9CEA17E-9827-4408-B992-26A5546BC969}"
	ProjectSection(ProjectDependencies) = postProject
		{FB9D1617-AC45-4CF9-B66B-FE3E53C0E992} = {FB9D1617-AC45-4CF9-B66B-FE3E53C0E992}
	EndProjectSection
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{FB9D1617-AC45-4CF9-B66B-FE3E53C0E992}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{FB9D1617-AC45-4CF9-B66B-FE3E53C0E992}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{FB9D1617-AC45-4CF9-B66B-FE3E53C0E992}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{FB9D1617-AC45-4CF9-B66B-FE3E53C0E992}.Release|Any CPU.Build.0 = Release|Any CPU
		{A9CEA17E-9827-4408-B992-26A5546BC969}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{A9CEA17E-9827-4408-B992-26A5546BC969}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{A9CEA17E-9827-4408-B992-26A5546BC969}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{A9CEA17E-9827-4408-B992-26A5546BC969}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {5355614A-7FEE-498D-88FD-773B9C8497EE}
	EndGlobalSection
EndGlobal

标签:xml,linqtoxml,Elements,读取,XElement,Element,student,new,string
From: https://www.cnblogs.com/zhuoss/p/18410444

相关文章

  • C# 操作xml(转)
    四、xml1、概念:XML可扩展的标记语言类似于HTMLXML:存储数据注意:XM工是严格区分大小写的。XML标签也是成对出现的。2、通过代码来创建xML文档1、引用命名空间usingSystem.Xml;2、创建XML文档对象XmlDocumentdoc=newXmlDocument();3、创建第一行描述信息,并且添......
  • MyBatis 3种 使用 SQL 语句的方式;注解方式、注解提供器方式、XML 配置方式
    结论:为了统一使用方式,建议采用XML配置的方式;MyBatis提供了多种配置和使用SQL语句的方式,主要包括:注解方式(如@Select)、注解提供器方式(如@SelectProvider)和XML配置方式。每种方式都有其独特的优缺点,适用于不同的场景。以下是这三种方式的详细对比:1.@Select这类注解优点:......
  • YAML 与 JSON、XML 比较及 YAML 使用最佳实践
    YAML(YAMLAin'tMarkupLanguage的递归缩写)是一种人类可读的数据序列化格式,通常用于配置文件、数据交换和设置管理。它简洁且易于读写,尤其适合在编程语言之间传递配置数据。以下是一些YAML的基本概念和语法示例:基本语法键值对:name:JohnDoeage:30嵌套:person:name:JohnDoe......
  • C/C++ 学生管理系统的文件读取与写入
    代码中文件读取函数read_file()存在一些问题,望指出.`#includeincludedefineSIZE100usingnamespacestd;staticintnums_stu=0;typedefstructStudent{char*name;char*ID; //占10个字符doublescore_one;doublescore_two;doublescore_three;doubletota......
  • C++读取命令行参数的学习(BOOST库)
    在c++工程中,经常需要通过命令行参数来获取程序运行所需要的信息。作者在实际工作中学习了Boost库,这里根据作者的理解,写了一个依托boost库完成命令行参数提取的程序模版,请大佬批评!!#defineOK0#defineExit-99//主程序#include<iostream>#include"XApp.h"intmain(int......
  • dotnet OpenXML SDK 添加 CoreFilePropertiesPart 的方法
    本文记录在OpenXMLSDK2.15版本下,为PPTX文件添加CoreFilePropertiesPart的方法,通过本文的方法可以正确且简单的添加core.xml文件到PPTX文件里当前的OpenXMLSDK存在已知问题,那就是默认情况下生成不包含core.xml文件,请参阅https://github.com/dotnet/Open-XML-SDK......
  • Python文件操作:文件的读取和写入(文本文件、二进制文件)①
    文章目录1.文件操作基础1.1打开文件1.2关闭文件2.文本文件操作2.1读取文本文件2.1.1逐行读取2.1.2读取所有内容2.1.3读取所有行2.2写入文本文件2.2.1写入内容2.2.2追加内容3.二进制文件操作3.1读取二进制文件3.2写入二进制文件4.综合示例4.1示例描......
  • PbootCMS生成的sitemap.xml中增加tag标签链接
    //指定分类标签调用publicfunctiongetSortTags($scode){$join=array(array('ay_content_sortb','a.scode=b.scode','LEFT'),array('ay_modelc......
  • Mybatis读取和存储json类型的数据
    目录一、测试使用JSONObject来获取json二、设置@TableName的autoResultMap为true,@TableField的typeHandler为JacksonTypeHandler.class三、设置xml当中的resultMap四、JacksonTypeHandler讲解五、新增假如是JSONObject异常问题六、遇到转义的问题不管数据库当中是以json还是longte......
  • 微信小程序开发系列7----页面配置--WXML的include用法
       传递变量   模板不能引用 ......