C#文本txt转xml
关于原文博主提供的代码运行中出现的问题,进行了一些修正~
原文链接:https://blog.csdn.net/chuangxin/article/details/5336756/
1.将txt内容转为xml格式内容部分报语法错误:
sb.Append("<?xml version=/"1.0/" encoding=/"gbk/"?>").Append(Environment.NewLine).Append("<dataRoot>").Append(Environment.NewLine);
这是因为斜杠方向反了,应修改为:
sb.Append("<?xml version=\"1.0\" encoding=\"gbk\"?>").Append(Environment.NewLine).Append("<dataRoot>").Append(Environment.NewLine);
通过查看原文文末xml文件可以看出,这一段代码的作用是生成xml第一行,其中“1.0”和“gbk”都带双引号“”,在编程过程中,为了跟字符串所用引号“”区分开,需要对双引号“”转义,所以要用反斜杠加引号,即\" 。
2.将txt内容转为xml格式内容部分,同理,转义字符要用反斜杠
//将txt内容分解为行数组
String[] lines = this.txtTXT.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
String[] heads = null;
if (lines != null && lines.Length > 0)
{
//读取第一行数据,该行数据为xml文件的节点描述数据
heads = lines[0].Split(new string[] { "\t" }, StringSplitOptions.None);
//MessageBox.Show(heads.Length.ToString() + " " + heads[0]);
}
“\r\n"表示按照换行符识别换行,”\t"表示按照制表符tab分割一行中的字符。
3.生成的xml文件打开报错
This page contains the following errors:
error on line 1 at column 19: String not closed expecting " or ’
Below is a rendering of the page up to the first error.
这是因为在产生xml节点部分,createNode函数中这一部分带来的隐患:
for (int i = 0; i < head.Length; i++)
{
sb.Append("<" + head[i] + ">" + info[i] + "</" + head[i] + ">").Append(Environment.NewLine);
}
如果txt文件中的内容包含未转义的特殊字符(如‘<’,‘>’,'&'等),会导致xml格式错误,因此在添加xml节点时,需要对这些字符转义,这是修改后的代码:
private String createNode(String[] head, String[] info)
{
StringBuilder sb = new StringBuilder();
sb.Append("<record>").Append(Environment.NewLine);
for (int i = 0; i < head.Length; i++)
{
sb.Append("<" + System.Security.SecurityElement.Escape(head[i]) + ">" + System.Security.SecurityElement.Escape(info[i]) + "</" + System.Security.SecurityElement.Escape(head[i]) + ">").Append(Environment.NewLine);
}
sb.Append("</record>").Append(Environment.NewLine);
return sb.ToString();
}
4.以下是修改后的全部代码:
using System.Text;
namespace WinForms1
{
public partial class FrmTxtXml : Form
{
public FrmTxtXml()
{
InitializeComponent();
}
//打开txt文件
private void toolStripOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
fileDialog.Filter = "文本文件(*.txt)|*.txt";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
String fileName = fileDialog.FileName;
if (!String.IsNullOrEmpty(fileName))
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using (StreamReader st = new StreamReader(fileName, System.Text.Encoding.GetEncoding("GBK")))
{
String txtContent = st.ReadToEnd();
//读取txt文件到txtTXT文本框
this.txtTXT.Text = txtContent;
st.Close();
}
}
}
}
}
//将txt内容转换为xml格式内容
private void toolStripeConvert_Click(object sender, EventArgs e)
{
try
{
//将txt内容分解为行数组
String[] lines = this.txtTXT.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
String[] heads = null;
if (lines != null && lines.Length > 0)
{
//读取第一行数据,该行数据为xml文件的节点描述数据
heads = lines[0].Split(new string[] { "\t" }, StringSplitOptions.None);
//MessageBox.Show(heads.Length.ToString() + " " + heads[0]);
}
//
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"gbk\"?>").Append(Environment.NewLine).Append("<dataRoot>").Append(Environment.NewLine);
//生成xml节点
for (int i = 1; i < lines.Length; i++)
{
if (lines[i] == null || lines[i].Trim().Length < 1)
continue;
String[] info = lines[i].Split(new string[] { "\t" }, StringSplitOptions.None);
sb.Append(createNode(heads, info));
}
sb.Append("</dataRoot>");
this.txtXML.Text = sb.ToString();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
//产生xml节点
private String createNode(String[] head, String[] info)
{
StringBuilder sb = new StringBuilder();
sb.Append("<record>").Append(Environment.NewLine);
for (int i = 0; i < head.Length; i++)
{
sb.Append("<" + System.Security.SecurityElement.Escape(head[i]) + ">" + System.Security.SecurityElement.Escape(info[i]) + "</" + System.Security.SecurityElement.Escape(head[i]) + ">").Append(Environment.NewLine);
}
sb.Append("</record>").Append(Environment.NewLine);
return sb.ToString();
}
// 将txtXML文本内容另存为xml文件
private void toolStripSaves_Click(object sender, EventArgs e)
{
try
{
String fileName = "";
using (SaveFileDialog fileDialog = new SaveFileDialog())
{
fileDialog.Filter = "XML数据文件(*.xml)|*.xml";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
fileName = fileDialog.FileName;
if (!String.IsNullOrEmpty(fileName))
{
FileStream fs = new FileStream(fileName, FileMode.Create);
//获得字节数组
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
byte[] data = System.Text.Encoding.GetEncoding("GBK").GetBytes(this.txtXML.Text);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
}
}
MessageBox.Show(String.Format("文件成功保存到{0}", fileName));
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
}
再次声明,原文链接:https://blog.csdn.net/chuangxin/article/details/5336756/