读取XML,对属性进行排序,然后写入文本文件c#

本文关键字:文本 文件 然后 XML 属性 读取 排序 | 更新日期: 2023-09-27 18:21:36

作为c#的初学者:我在谷歌上搜索了一下,但在一个"简单问题"中迷路了:

Read a XML : 
    <persons>        this is sample 
      <person id="0">
        <Lname>Johnson</Lname>
        <Fname>Molly</Fname>
      </person>
      <person id="1">
        <Lname>buffalo</Lname>
        <Fname>Mike</Fname>
      </person>
      <person id="2">
        <Lname>COOLS</Lname>
        <Fname>WALTER</Fname>
      </person>
      <person id="3">
        <Lname>FROMUS</Lname>
        <Fname>LUDOVICUS</Fname>
    </persons>

我需要按Lname(姓氏)和Fname(名字)排序
并在文本文件(txt)中列出有

例如,你看到两个人都有约克的名字,所以就按名字排序。

 Case John
 Buffalo Mike
 York Theo
 York Viviane

Lname和Fname应该在同一行上,但为下一个Lname Fname使用新行
这不是这个问题,因为这个工具中有语法问题(对不起)

附加信息:我试图使用foreach和var指令来列出,但被搞砸了。目标是尽可能多地使用LINQ和OO(面向对象)。

非常感谢

我对评论的回应:


首先,我想为错误的XML道歉——最后一个标记有一个错误的/符号。语言确实是荷兰语(荷兰)——我把标签名称改成了英语。

我已经拥有的是读取XML文件并根据属性"id"进行排序,然后写入一个平面文件。然后,我试图通过使用orderby.来练习"foreach var构造",使其更加面向对象

我现在拥有的代码:

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Xml;
using System.Net;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
       XmlReader reader = XmlReader.Create("c:/download/test.xml");
            List<string> Collectperson = new List<string>();
            Collectperson.Clear();
            string personid = "";
            string nm = "";
            string vn = "";
            string oneline = "";
            while (reader.Read())
            {
                if (reader.NodeType != XmlNodeType.EndElement)
                {
                    // Get element name and switch on it.
                    switch (reader.Name)
                    {
                        case "persoon":
                            // Detect this element.
                            // initialize collectperson 
                            Collectperson.Clear();
                            Console.WriteLine(" " + reader.GetAttribute(0));
                            Collectperson.Add(reader.GetAttribute(0));
                            //   add to  file ans reinitialize string 
                            oneline = "";
                            oneline = string.Join(" ", Collectperson.ToArray());
                            break;
                        //
                        case "naam":
                            if (reader.Read())
                            {
                                Console.WriteLine(reader.Value);
                                nm = reader.Value;
                                Collectperson.Add(nm);
                                oneline = string.Join(" ", Collectperson.ToArray());
                            }
                            break;
                        case "voornaam":
                            if (reader.Read())
                            {
                                Console.WriteLine(reader.Value);
                                vn = reader.Value;
                                Collectperson.Add(vn);
                                oneline = string.Join(" ", Collectperson.ToArray());
         // ==================================================================================
                                string path = @"c:/download/personen.txt";
                                // This text is added only once to the file. 
                                if (!File.Exists(path))
                                {
                                    // Create a file to write to. 
                                    using (StreamWriter sw = File.CreateText(path))
                                    {
                                        sw.WriteLine(oneline);
                                    }
                                }
                                // This text is always added, making the file longer over time 
                                // if it is not deleted. 
                                using (StreamWriter sw = File.AppendText(path))
                                {
                                    sw.WriteLine(oneline);
                                }
        //==================================================================================
                            }
                            break;
                    }  // switch
                }
            }  // while 
        }
    }
}

读取XML,对属性进行排序,然后写入文本文件c#

要将xml文件加载到模型中,可以使用XmlSerializer.Deserialize

using (var sw = new StreamReader(iPathToXMLFile, Encoding.Default))
{
    var ser = new XmlSerializer(typeof(T));
    val = (T)ser.Deserialize(sw);
}

然后,您可以为"person"对象创建一个类,然后实现IComparable,以便能够对人员列表进行排序:)例如:如何对自定义类的数组进行排序?

[编辑1]

另一种方式:

public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}
var list = new List<Person>
{
    new Person {FirstName = "Viviane", LastName = "York"},
    new Person {FirstName = "Mike", LastName = "Buffalo"},
    new Person {FirstName = "Theo", LastName = "York"},
    new Person {FirstName = "John", LastName = "Case"}
};
var sorted = list.OrderBy( p => p.LastName).ThenBy( p => p.FirstName).ToList();

[EDIT2]:I可比较的解决方案

public class Person : IComparable<Person>
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public int CompareTo(Person obj)
    {
        var val = String.Compare(LastName, obj.LastName, StringComparison.Ordinal);
        // Same LastName case
        if (0 == val)
            val = String.Compare(FirstName, obj.FirstName, StringComparison.Ordinal);
        return val;
    }
}
        var list = new List<Person>
        {
             new Person {FirstName = "Viviane", LastName = "York"},
            new Person {FirstName = "Mike", LastName = "Buffalo"},
            new Person {FirstName = "Theo", LastName = "York"},
            new Person {FirstName = "John", LastName = "Case"}
        };

        list.Sort(); // Sort will call IComparable implementation of the Person class

[编辑3]

您也可以使用IComparer,代理人。。。我让你在网上搜索这个。

此视频可能会帮助您。他解释了先使用XML,然后使用Json。我更喜欢Json,你也可以看完这个。Bob Tabor解释得很好。希望这能引导你走上正轨。

<lt;存储和检索序列化数据>>