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. Filebeat的使用

    前言 logstash本身就可以具有文件数据采集的功能了,为什么还需要在前面加一层filebeat?理由如下:logstash是使用Java编写,插件是使用JRuby编写,对机器的资源要求会比较高,在 ...

  2. HandlerMethodReturnValueHandler SpringMVC 参数解析 继承关系以及各解析器解析类型

    I HandlerMethodReturnValueHandler (org.springframework.web.method.support) AbstractMessageConverterM ...

  3. java Random 带权重的随机选择

    实际场景中,经常要从多个选项中随机选择一个,不过,不同选项经常有不同的权重. /** * Created by xc on 2019/11/23 * 带权重的随机选择 */ public class ...

  4. vbscript--FileSystemObject详解

    https://blog.csdn.net/superbirds/article/details/6762748 FSO是FileSystemObject 或 Scripting.FileSystem ...

  5. Django Model 模型

    参考: https://www.runoob.com/django/django-model.html https://www.cnblogs.com/taosiyu/p/11260000.html ...

  6. mvn-dependencies-vs-dependencyManagement

    dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显式的声明需要用的依赖. dependencies 相对于dependencyManagement,所有声明在dep ...

  7. myeclipse An internal error occurred during: "Initialize metrics".

    重新安装的myeclipse,在打开的时候弹出:    An internal error occurred during: "Initialize metrics". com/g ...

  8. SaltStack 是一个服务器基础架构集中化管理平台

    SaltStack详细部署   一.基础介绍============================================================================== ...

  9. 编译器的系统include路径查询

    环境:Ubuntu 18.04.3 LTS 以 aarch64-linux-gnu-gcc 为例,运行如下命令: echo "main(){}" | aarch64-linux-g ...

  10. XXE任意文件读取(当xml解析内容有输出时)

    利用XXE漏洞读取文件 参考:https://www.jianshu.com/p/4fc721398e97 首先找到登录源码如下: 由题目可以利用XXE漏洞读取文件 先登录用Burp Suite抓包: ...