【问题标题】:read XML , sort on attribute and write to text file c#读取 XML,按属性排序并写入文本文件 c#
【发布时间】:2014-09-13 00:26:29
【问题描述】:

作为 c# 的初学者:我在 Google 上四处搜索,但在一个“简单的问题”中迷失了方向:

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) 中列出 有

例如你看 2 人的 Lname 是 York,所以按 Fname 排序。

 Case John
 Buffalo Mike
 York Theo
 York Viviane

Lname 和 Fname 应该在同一行,但下一个 Lname 和 Fname 换一个新行。
由于此工具中存在语法问题,因此不在此问题中(对不起)

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

非常感谢

我对 cme​​ts 的回应:


首先我要为格式错误的 XML 道歉——最后一个标签有一个错误的 / 符号。 该语言确实是荷兰语(荷兰)-我将标签名称更改为英语。

我已经拥有的是读取 XML 文件并对属性“id”进行排序并写入平面文件。然后我尝试通过使用 orderedby 练习“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,如何排序,以及如何写入文本文件。你试过把它拆开吗?
  • 那个 xml 无效。您的结尾personen 标记不正确,persoon id="3" 没有结尾标记。
  • 1.标点符号和拼写是表明你付出了一些努力的好方法。 2. 分解(读取 xml、排序、写入),然后寻找各个问题的答案。这些问题以前被问过,并不难找到

标签: c#


【解决方案1】:

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

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

那么,您可以为“person”对象创建一个类,然后实现 IComparable 以便能够对人员列表进行排序 :) 例如:How do I sort an array of custom classes?

[编辑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] : IComparable 解决方案

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,委托人...我让你在网上搜索这个。

【讨论】:

  • @DJKRAZE 我敢打赌,不管你想要那个人是一个对象
  • @DJKRAZE,不幸的是,示例 xml 的拼写正确。
  • @DJKRAZE XML 是另一种语言。见“voornaam”
  • 好吧,看看 xml,“personen”看起来像一个名为“persoon”的对象的集合,具有至少 3 个公共属性:id、LName、FName。这只是猜测,抱歉。看起来像荷兰语。
  • 我认为你是对的 eddie_cat 只是看起来很奇怪
【解决方案2】:

此视频可能会对您有所帮助。他解释了先使用 XML,然后再使用 Json。我更喜欢 Json,你也可能看过这个。 Bob Tabor 很好地解释了事情。希望这能引导您走上正确的道路。

Storing and retrieving Serialized Data>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多