C#使用XmlTextReader和XmlTextWriter格式化Xml字符串,使得Xml字符串美观,
即增加换行和缩进。
新建控制台程序FormatXmlDemo,输入如下代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace FormatXmlDemo
{
class Program
{
static void Main(string[] args)
{
Console.SetWindowSize(120, 30);
string srcXml = $@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:web=""http://WebXml.com.cn/"">
<soapenv:Header/>
<soapenv:Body>
<web:getWeatherbyCityName><web:theCityName>深圳</web:theCityName></web:getWeatherbyCityName>
</soapenv:Body>
</soapenv:Envelope>";
Console.WriteLine("初始源XML字符串");
Console.WriteLine(srcXml);
Console.WriteLine("--------------------------------格式化后的XML字符串--------------------------------");
string formattedXml = FormatXml(srcXml);
Console.WriteLine(formattedXml);
Console.ReadLine();
}
/// <summary>
/// 对xml节点进行换行,格式化对齐操作
/// </summary>
/// <param name="srcXml"></param>
/// <returns></returns>
public static string FormatXml(string srcXml)
{
string formattedXml = IndentedFormat(IndentedFormat(srcXml).Replace("><", ">\r\n<"));
return formattedXml;
}
/// <summary>
/// 对XML字符串进行换行缩进,格式化
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
private static string IndentedFormat(string xml)
{
string indentedText = string.Empty;
try
{
XmlTextReader reader = new XmlTextReader(new StringReader(xml));
reader.WhitespaceHandling = WhitespaceHandling.None;
StringWriter indentedXmlWriter = new StringWriter();
XmlTextWriter writer = CreateXmlTextWriter(indentedXmlWriter);
writer.WriteNode(reader, false);
writer.Flush();
indentedText = indentedXmlWriter.ToString();
}
catch (Exception)
{
indentedText = xml;
}
return indentedText;
}
/// <summary>
/// 写入四个缩进字符【空格】
/// </summary>
/// <param name="textWriter"></param>
/// <returns></returns>
private static XmlTextWriter CreateXmlTextWriter(TextWriter textWriter)
{
XmlTextWriter writer = new XmlTextWriter(textWriter);
//将Tab转化为4个空格
bool convertTabsToSpaces = true;
if (convertTabsToSpaces)
{
writer.Indentation = 4;
writer.IndentChar = ' ';
}
else
{
writer.Indentation = 1;
writer.IndentChar = '\t';
}
writer.Formatting = Formatting.Indented;
return writer;
}
}
}
程序运行如图:


3160

被折叠的 条评论
为什么被折叠?



