XML整形

估计如下一样使用XDocument的人比较多,毕竟也是微软推荐使用的。

        string FormatXml(string Xml)
{
try
{
XDocument doc = XDocument.Parse(Xml);
return doc.ToString();
}
catch (Exception)
{
return Xml;
}
}

当出现如下文档(默认命名空间,前缀命名空间都定义)时,以上方法返回的值格式变了:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Created>2015-06-05T18:19:34Z</Created>
<LastSaved>2015-06-05T18:19:39Z</LastSaved>
<Version>16.00</Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<AllowPNG/>
<RemovePersonalInformation/>
</OfficeDocumentSettings>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>12645</WindowHeight>
<WindowWidth>22260</WindowWidth>
<WindowTopX>1170</WindowTopX>
<WindowTopY>0</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font ss:FontName="游ゴシック" x:CharSet="128" x:Family="Modern" ss:Size="11"
ss:Color="#000000"/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
<Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1"
x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="18.75">
</Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<PageSetup>
<Header x:Margin="0.3"/>
<Footer x:Margin="0.3"/>
<PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
</PageSetup>
<Print>
<ValidPrinterInfo/>
<PaperSizeIndex>9</PaperSizeIndex>
<HorizontalResolution>600</HorizontalResolution>
<VerticalResolution>600</VerticalResolution>
</Print>
<Selected/>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>

XDocument整形之后,前缀显示自动加上了:

<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="Excel.Sheet"?>
<ss:Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Created>2015-06-05T18:19:34Z</Created>
<LastSaved>2015-06-05T18:19:39Z</LastSaved>
<Version>16.00</Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<AllowPNG />
<RemovePersonalInformation />
</OfficeDocumentSettings>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>12645</WindowHeight>
<WindowWidth>22260</WindowWidth>
<WindowTopX>1170</WindowTopX>
<WindowTopY>0</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<ss:Styles>
<ss:Style ss:ID="Default" ss:Name="Normal">
<ss:Alignment ss:Vertical="Bottom" />
<ss:Borders />
<ss:Font ss:FontName="游ゴシック" x:CharSet="128" x:Family="Modern" ss:Size="11" ss:Color="#000000" />
<ss:Interior />
<ss:NumberFormat />
<ss:Protection />
</ss:Style>
</ss:Styles>
<ss:Worksheet ss:Name="Sheet1">
<ss:Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="18.75"></ss:Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<PageSetup>
<Header x:Margin="0.3" />
<Footer x:Margin="0.3" />
<PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75" />
</PageSetup>
<Print>
<ValidPrinterInfo />
<PaperSizeIndex>9</PaperSizeIndex>
<HorizontalResolution>600</HorizontalResolution>
<VerticalResolution>600</VerticalResolution>
</Print>
<Selected />
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</ss:Worksheet>
</ss:Workbook>

解决办法:使用XmlDocument

        static string FormatXml(string xml)
{
try
{
var doc = new XmlDocument();
doc.LoadXml(xml); StringBuilder output = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
Async = true
};
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
doc.Save(writer);
}
return output.ToString();
}
catch (Exception)
{
return xml;
}
}

整形之后保持原样:

<?xml version="1.0" encoding="utf-16"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Created>2015-06-05T18:19:34Z</Created>
<LastSaved>2015-06-05T18:19:39Z</LastSaved>
<Version>16.00</Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<AllowPNG />
<RemovePersonalInformation />
</OfficeDocumentSettings>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>12645</WindowHeight>
<WindowWidth>22260</WindowWidth>
<WindowTopX>1170</WindowTopX>
<WindowTopY>0</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom" />
<Borders />
<Font ss:FontName="游ゴシック" x:CharSet="128" x:Family="Modern" ss:Size="11" ss:Color="#000000" />
<Interior />
<NumberFormat />
<Protection />
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
<Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="18.75"></Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<PageSetup>
<Header x:Margin="0.3" />
<Footer x:Margin="0.3" />
<PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75" />
</PageSetup>
<Print>
<ValidPrinterInfo />
<PaperSizeIndex>9</PaperSizeIndex>
<HorizontalResolution>600</HorizontalResolution>
<VerticalResolution>600</VerticalResolution>
</Print>
<Selected />
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>

改行(CR+LF)问题

标签的值中如果包含\r\n换行符,XDocument以及XmlDocument读取之后会默认被转换为\n,如果就这样保存会少了\r。

而且Excel另存为的xml格式文件中的改行符为【 】,很难直接复原。

如果不在意xml格式的话可以通过如下方法解决:

        static string FormatXml(string xml)
{
try
{
var doc = new XmlDocument();
doc.LoadXml(xml); StringBuilder output = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
NewLineChars = "\r\n",
NewLineOnAttributes = true,
NewLineHandling = NewLineHandling.Replace,
CheckCharacters = false,
Indent = false,
Async = true
};
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
doc.Save(writer);
}
return output.ToString();
}
catch (Exception)
{
return xml;
}
}

XML整形以及改行字符串输出的更多相关文章

  1. 将filenames里的每个字符串输出到out文件对象中注意行首的缩进

    在Linux上用强大的shell脚本应该也可以完成,可是使用Windows的朋友呢?其实象这样一个简单任务用Python这个强大脚本语言只要几条语句就可以搞定了.个大家知道,要完成这样一个任务根本不用 ...

  2. Winform: use the WebBrowser to display XML with xslt, xml, xslt 转 html 字符串

    原文:Winform: use the WebBrowser to display XML with xslt, xml, xslt 转 html 字符串 声明xml字符串: string xml = ...

  3. 【转】xml节点解析成字符串的方法

    网址:http://blog.csdn.net/shanzhizi/article/details/8817532 ZC: 这是 libxml2的 之前汇总了一篇关于xml文档与字符串转换的文章,文章 ...

  4. 批处理将字符串输出到Windows剪贴板

    批处理将字符串输出到Windows剪贴板 2016-06-30 23:29 339人阅读 评论(0) 收藏 举报 版权声明:作者:N3verL4nd 出处:http://blog.csdn.net/x ...

  5. 8 C#中的字符串输出

    我们在前面已经用Console.WriteLine("*********")往dos窗口中输出过字符串.我们还定义过字符串的变量. string words ="我喜欢D ...

  6. 《c程序设计语言》读书笔记--大于8 的字符串输出

    #include <stdio.h> #define MAXLINE 100 #define MAX 8 int getline(char line[],int maxline); voi ...

  7. implode 多维数组转一维数组并字符串输出

    //多维数组返回一维数组,拼接字符串输出 public function r_implode( $glue, $pieces ) { foreach( $pieces as $r_pieces ) { ...

  8. Python学习笔记 (2) :字符串输出、操作、格式化和日期、时间格式化

    一.字符串输出及运算 1.常用输出格式及方法 ')#单引号 ")#双引号 """)#三个引号 1234567890 1234567890 1234567890 ...

  9. repr方法字符串输出实例对象的值

    #coding=utf-8 #repr方法字符串输出实例对象的值 class CountFromBy(object): def __init__(self, val=0, incr=1): self. ...

随机推荐

  1. 面试突击(八)——JVM的结构及内存模型,是怎么划分的?

    声明:本文图片均来自网络,我只是进行了选择,利用一图胜千言的力量来帮助自己快速的回忆相关的知识点 0:再上一张Java代码的转换流程图 .java——Java程序员编写,给人看的 .class——Ja ...

  2. Mac安装MySQL-python的血泪史

    现象描述 起初正常使用pip命令提示如下的错误: cc -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.14-intel- ...

  3. java js ur特殊格式处理 json 特殊格式处理

    url特殊格式处理: js中使用 encodeURIComponent() 编码对应的value $.ajax({ type: "post", url: "/tb_are ...

  4. [转]How to Install Oracle Java 11 in Ubuntu 18.04/18.10

    链接地址:http://ubuntuhandbook.org/index.php/2018/11/how-to-install-oracle-java-11-in-ubuntu-18-04-18-10 ...

  5. 深入nginx之《获取用户的真实IP》

    获取用户的真实IP Nginx会将客户端的IP信息存放在$remote_addr变量里,但这并不意味着它就是客户端的IP,生产环境往往会充满各种代理,让IP的来龙去脉变得扑朔迷离. 目前互联网公司基本 ...

  6. .net for TCP服务端 && 客户端

    关键代码 详细代码请看示例代码 Service //创建套接字 IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ipaddress), port); / ...

  7. 使excel中的表头一直显示

    视图 -- 冻结单元格 https://jingyan.baidu.com/article/fedf073788db6b35ac89779a.html

  8. 后端&前端零碎知识点和注意问题

    后端 1. Spring自带的MD5加密工具类 import org.springframework.util.DigestUtils; String md5Password = DigestUtil ...

  9. 域名解析中的cname解析和显性URL跳转和隐性URL跳转三者有什么区别

    通俗的来讲,cname解析还是属于dns解析,只是把某个域名解析到另外一个域名对应的某个IP的空间中,所以还需要在服务器端(比如nginx)做域名解析(比如把baidu.com做一个cname解析到i ...

  10. SGU 126. Boxes --- 模拟

    <传送门> 126. Boxes time limit per test: 0.25 sec. memory limit per test: 4096 KB There are two b ...