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. 【Python】解析Python中函数的基本使用

    1.简介 在Python中定义函数的基本格式为: def <函数名>(参数列表): <函数语句> return <返回值> Python中的函数形式比较灵活,声明一 ...

  2. odoo开发笔记 -- odoo快速开发技巧

    1. 需求分析到位 2. 系统对接,角色用例,数据串接 ---确定,轻易不可变更 3. 业务流程拆分细化 出图--开发人员理解的地步 4. 数据模型建立 --对应角色用例 5. 确立开发计划,划分功能 ...

  3. Xcode7.2真机测试问题"The account 'appleID ' has no team with ID ‘’

     在Xcode7(测试版)提出免费真机测试的时候,我立刻在网上搜寻测试步骤,很简单,按照步骤走就可以. 但在7.2以后,突然我的iPhone不能真调了!提示"The account 'app ...

  4. spring boot2X整合Consul一服务注册与发现

    Consul 是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置. 关键特性: 服务注册/发现 数据强一致性保证 多数据中心 健康检查 key/value存储 1.下载 htt ...

  5. Servlet3.0对异步处理的支持

    Servlet工作流程 Servlet 3.0 之前,一个普通 Servlet 的主要工作流程大致如下: Servlet 接收到请求之后,可能需要对请求携带的数据进行一些预处理: 调用业务接口的某些方 ...

  6. 安卓学习日记第二天——Fragment

    一.基本概念 Fragment是依赖于Activity的,不能独立存在的. 一个Activity里可以有多个Fragment. 一个Fragment可以被多个Activity重用. Fragment有 ...

  7. 手撕面试官系列(三):微服务架构Dubbo+Spring Boot+Spring Cloud

    文章首发于今日头条:https://www.toutiao.com/i6712696637623370248/ 直接进入主题 Dubbo (答案领取方式见侧边栏) Dubbo 中 中 zookeepe ...

  8. C++和c语言的区别

    在大家眼中c++与C语言很像,但两个有本质的区别,C语言是面向过程的,而C++是面向对象的,下面就给大家梳理梳理. 1.C语言有标准的函数库,它们松散的,只是把功能相同的函数放在一个头文件中:而C++ ...

  9. mPass多租户系统微服务开发平台

    目录 项目总体架构图 基于SpringBoot2.x.SpringCloud并采用前后端分离的企业级微服务,多租户系统架构微服务开发平台 mPaaS(Microservice PaaS)为租户业务开发 ...

  10. MySQL单表数据量过千万,采坑优化记录,完美解决方案

    问题概述 使用阿里云rds for MySQL数据库(就是MySQL5.6版本),有个用户上网记录表6个月的数据量近2000万,保留最近一年的数据量达到4000万,查询速度极慢,日常卡死.严重影响业务 ...