string sFile = "testxml2ss.xml"; try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(sFile);
XmlTextWriter writer = new XmlTextWriter (sFile, System.Text.Encoding.Default);
writer.Formatting = Formatting.Indented;
writer.Indentation=4;
xmldoc.Save(writer);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message,"Something is wrong");
}
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(sFile);
XmlTextWriter writer = new XmlTextWriter (sFile, System.Text.Encoding.Default);
writer.Formatting = Formatting.Indented;
writer.Indentation=4;
xmldoc.Save(writer);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message,"Something is wrong");
}
其实这句话好象用处不大
writer.Indentation=4;
在writer.Formatting = Formatting.Indented;就已经正确格式了
XML它有自己的错误处理的含数么|?
~~~~~~~~~~~~~~~~~~
这一句有问题吧,你需要测试一下sFile指向的文件究竟存不存在,
{
System.Windows.Forms.MessageBox.Show(e.Message,"Something is wrong");
}
就是捕获错误的啊。如果没有就报错。
using System;
using System.Xml;
namespace xmlsaveload
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class xmlPrettyPrint
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
public static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Console.Write ("输入两个参数一个是打开的文件名另一个是保存的文件名:");
string sFile = args[0]+".xml";
//Create XmlDocumnet Object
try
{ XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sFile);
//sFile为要求写入的文件名,如果该文件擦存在,就会截断该文件进行修该)
XmlTextWriter writer = new XmlTextWriter (sFile, System.Text.Encoding.Default);
//说明要求缩进,和缩进的级别 IndentChar 的数目
writer.Formatting = Formatting.Indented;
//writer.Indentation=4;
//Let xml file save to appoint xmlWriter
string sXml = args[1];
if (sFile==sXml)
{
xmlDoc.Save(writer.BaseStream);
}
else
{
xmlDoc.Save(sXml+".xml");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message,"Something is wrong");
} }
}
}
using System.Xml;
using System.IO;namespace xmlsaveload
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class xmlPrettyPrint
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
public static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
try
{
string sFile = args[0]+".xml";
//Create XmlDocumnet Object
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sFile);
XmlTextWriter writer = new XmlTextWriter (sFile, System.Text.Encoding.Default);
//说明要求缩进,和缩进的级别 IndentChar 的数目
writer.Formatting = Formatting.Indented;
writer.Indentation=4;
//Let xml file save to appoint xmlWriter if (args[0]==args[1])
{
xmlDoc.Save(writer.BaseStream);
}
else
{
xmlDoc.Save(writer.BaseStream);
xmlDoc.Save(args[1]+".xml");
}
Console.WriteLine("转换成功!");
}
//sFile为要求写入的文件名,如果该文件擦存在,就会截断该文件进行修该)
catch (Exception e)
{
Console.WriteLine (e.Message);
} }
}
}
但是以上海存在一个问题就是:要保证.XML是正确的格式的,而且必须是.XML文件。就存在局限性,如果是HTML文件或不标准的.XML文件的话就无能为力了。郁闷啊~~~~~~~~~请问那个高手可以完成这个功能么?
用以上的程序就无法去作用了。我是想用正则表达式去找"<"和">"“</”,
每找到">"就加“\n”ruRUGUO如果是"<"就加"\t"根据需要来缩进几个"\t".利用堆栈的方先进后出的原则来做,可问题就是堆栈不会,不知道怎么去做。不知道我这个想法可不可以实现。