输入txt,输出xml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
using System.Collections;
namespace 输入txt输出xml
{
internal class Program
{
static void Main(string[] args)
{
TxtToXml();
}
public static void TxtToXml()
{
//读文件
//一行一行地读,然后将整个行字符串拆分为多个子串形成一个字符串数组
//记得这里要用Encoding.GetEncoding("utf-8"),不然会出现乱码
StreamReader sr = new StreamReader(File.Open(@"C:\Users\output.txt", FileMode.Open), Encoding.GetEncoding("utf-8"));
//ArrayList mydata = new ArrayList();
//输出到xml
//创建xml文档
//实例化一个xmldocument类
XmlDocument xDoc = new XmlDocument();
//声明一个xml所需要的语法的变量,添加在末尾
XmlDeclaration xmlDeclaration = xDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
//创建根节点
XmlElement element = xDoc.CreateElement("grades");
//添加根节点到xml文档去
xDoc.AppendChild(element);
while (true)
{
//读取每一行的数据
string line = sr.ReadLine();
if (line == string.Empty || line == null) break;
char[] separator = { ' ' };
//split:按照separate拆分成子串,返回给data字符串数组
string[] data = line.Split(separator);
//构造结点grade
XmlElement element1 = xDoc.CreateElement("grade");
//插入到根节点下
element.AppendChild(element1);
//学号
//创建grade下面的子节点Id
XmlElement element1_1 = xDoc.CreateElement("Id");
element1.AppendChild(element1_1);
element1_1.InnerText = data[0];
//姓名
XmlElement element1_2 = xDoc.CreateElement("Name");
element1.AppendChild(element1_2);
element1_2.InnerText = data[1];
//课程
XmlElement element1_3 = xDoc.CreateElement("Course");
element1.AppendChild(element1_3);
element1_3.InnerText = data[2];
//分数
XmlElement element1_4 = xDoc.CreateElement("Score");
element1.AppendChild(element1_4);
element1_4.InnerText = data[3];
//输出到grades.xml
xDoc.Save("grades.xml");
}
}
}
}
输入xml,输出txt
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
namespace 输入xml_输出txt
{
internal class Program
{
static void Main(string[] args)
{
XmlToTxt();
}
public static void XmlToTxt()
{
string[] str = new String[20];
XmlDocument xDoc = new XmlDocument();
xDoc.Load("C:/Users/grades.xml");
XmlNode node = xDoc.SelectSingleNode("grades");
XmlNodeList nodeList = node.ChildNodes;//取子节点集合
int i = 0;
foreach (XmlNode xn in nodeList)
{
XmlNodeList ChildList = xn.ChildNodes;//取子节点的子节点集合
foreach (XmlNode n in ChildList)
{
XmlElement xe = (XmlElement)n;
string classname = xe.Name;//标签名
string score = xe.InnerText;//内部文本
//Console.WriteLine(classname+":"+score);
str[i]=classname + ":" + score;
i++;
}
}
string outputPath = "C:/Users/input.txt";
File.WriteAllLines(outputPath, str);
Console.ReadKey();
}
}
}