任务描述:
将一个简单的文本格式的文件转变为一个自己定义的XML格式的文件。
开发语言:
C#(控制台程序)
文本文件格式:
学历教学计划,DeplomaTeachPlan
非学历专业进修教学计划,SubjectCertificateTeachPlan
将要转变后的XML格式的文件
xml version="1.0" encoding="gb2312" standalone="yes" ?>
< dataSheet >< data >< cnName > 学历教学计划 cnName>< enName > DeplomaTeachPlan enName>< description />< remark />< short />data>< data >< cnName > 非学历专业进修教学计划 cnName>< enName > SubjectCertificateTeachPlan enName>< description />< remark />< short />data><dataSheet>
原代码如下:
using System;
using System.IO;
using System.Xml;
namespace TextFiletoXml
{
///
/// 本程序是参照SDK的例子程序编写的。
///
class TextFiletoXml
{
public static String file;
public static StreamReader stream;
public static XmlTextWriter xwriter;
[STAThread]
static void Main(string[] args)
{
//第一个参数是将要转变的文本文件路径和名称
file = args[0];
//Create a new stream representing the file we are
//reading from.
stream = new StreamReader(file,System.Text.Encoding.GetEncoding("gb2312"),true);
//Create a new XmlTextWriter.将要创建的XML文件的名称
xwriter = new XmlTextWriter(args[1],System.Text.Encoding.GetEncoding("gb2312"));
//Write the beginning of the document including the
//document declaration. Standalone is true.
xwriter.WriteStartDocument(true);
//Write the beginning of the "data" element. This is
//the opening tag to our data
xwriter.WriteStartElement("dataSheet");
string input;
while ((input=stream.ReadLine())!=null)
{
string[] strContent = input.Split(',');
if (strContent.Length>=2)
{
xwriter.WriteStartElement("data");
xwriter.WriteElementString("cnName", strContent[0]);
xwriter.WriteElementString("enName", strContent[1]);
xwriter.WriteElementString("description"," ");
xwriter.WriteElementString("remark"," ");
xwriter.WriteElementString("short"," ");
xwriter.WriteEndElement();
}
}
//End the "data" element.
xwriter.WriteEndElement();
//End the document
xwriter.WriteEndDocument();
//Flush the xml document to the underlying stream and
//close the underlying stream. The data will not be
//written out to the stream until either the Flush()
//method is called or the Close() method is called.
xwriter.Close();
}
}
}