【发布时间】: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(面向对象)。
非常感谢
我对 cmets 的回应:
首先我要为格式错误的 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#