用xslt格式化指定的xml文件,以字符串格式输出,并保存。
config/Common.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="Common.xslt"?>
<configuration>
<services>
<service id="WNMS_KI" fileName="KPI.xml" filePath="~/config/KPI.xml" />
<service id="WNMS_PI" fileName="KPI.xml" filePath="~/config/TPI.xml" />
<service id="Test" fileName="test.xml" filePath="~/config/test.xml" />
</services>
</configuration>
config/KPI.xml 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<service id="WNMS_KI" compress="false" transfer="false" needHeader="true">
<select id="kpi" asparams="false" errInfo="">
select * from dual
</select>
</service>
<service id="WNMS_PI" compress="false" transfer="false" needHeader="true">
<select id="kpi" asparams="false" errInfo="">
select * from dual
</select>
</service>
</configuration>
config/Test.xml 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<service id="Test" compress="false" transfer="true" needHeader="true">
<select id="kpi_ct" asparams="false" errInfo="">
select '<>' test from dual
</select>
</service>
</configuration>
config/Common.xslt 文件
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--
此模板主要用于对根目录下的services/service节点进行排序,按id进行排序
-->
<xsl:template match="/">
<xsl:for-each select="services/service">
<xsl:sort data-type="text" order="ascending" select="@id"/>
<service>
<xsl:attribute name="id">
<xsl:value-of select="@id"/>
</xsl:attribute>
<xsl:attribute name="fileName">
<xsl:value-of select="@fileName"/>
</xsl:attribute>
<xsl:attribute name="filePath">
<xsl:value-of select="@filePath"/>
</xsl:attribute>
</service>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
ServiceManage.cs 文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.IO;
using System.Xml.XPath;
using System.Xml.Xsl;
/// <summary>
///ServiceManage 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class ServiceManage : System.Web.Services.WebService
{
string strCommandFileName = System.Web.HttpContext.Current.Server.MapPath("~/config/Common.xml");
//加载配置文件
XmlDocument xmlDocCommon = new XmlDocument();
// 所有WebService入口程序所在的节点
XmlNode myServiceNode;
public ServiceManage()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
/// <summary>
/// 为了提交WebService服务的效率,将所有WebService写入Common.xml文件中,用于快速定位
/// </summary>
/// <returns></returns>
[WebMethod]
public string MaintainService()
{
try
{
#region === 加载common.xml中的services节点 ===
this.xmlDocCommon.Load(strCommandFileName);
this.myServiceNode = this.xmlDocCommon.SelectSingleNode("configuration/services");
if (this.myServiceNode != null)
{
this.myServiceNode.InnerXml = "";
}
else
{
XmlElement xmlConfigration = this.xmlDocCommon.CreateElement("services");
this.myServiceNode = (XmlNode)xmlConfigration;
}
#endregion
#region 获取结果 ===
//获取所有config目录下的配置文件
GetDirectory(new DirectoryInfo(Server.MapPath("~/config/")));
//获取排序后的xml节点
this.myServiceNode.InnerXml = TransXSLT(this.myServiceNode, Server.MapPath("~/config/Common.xslt"));
// 保存文档
this.xmlDocCommon.Save(strCommandFileName);
#endregion
return "调用成功,重写所有WebService接口文件";
}
catch (Exception exp)
{
return "出错,信息如下:" + exp.Message;
}
}
#region === 追加所有service节点到myServiceNode节点 ===
/// <summary>
/// 追加所有service节点到myServiceNode节点
/// </summary>
/// <param name="dir">目录</param>
private void GetDirectory(DirectoryInfo dir)
{
try
{
//获取当前所有config目录下的配置文件
FileInfo[] files = dir.GetFiles();
for (int i = 0; i < files.Length; i++)
{
if (files[i].Extension.ToLower() == ".xml")
{
try
{
#region === 遍历每个xml文件,追加Service节点到myServiceNode节点中 ===
XmlDocument xmlDocService = new XmlDocument();
xmlDocService.Load(files[i].FullName);
XmlNodeList NodeService = xmlDocService.SelectNodes("configuration/service[@id and @instanceName and @xsd and @compress]");
for (int k = 0; k < NodeService.Count; k++)
{
XmlElement xeTemp = this.xmlDocCommon.CreateElement("service");
xeTemp.SetAttribute("id", NodeService[k].Attributes["id"].InnerText);
xeTemp.SetAttribute("fileName", files[i].Name);
xeTemp.SetAttribute("filePath", "~/config/" + files[i].FullName.Substring(files[i].FullName.IndexOf(@"\config\") + 8).Replace("\\", "/"));
this.myServiceNode.AppendChild((XmlNode)xeTemp);
}
#endregion
}
catch
{
//出错直接跳过此文件
}
}
}
#region === 遍历除temp目录外的所有目录 ===
DirectoryInfo[] arrDir = dir.GetDirectories();
for (int i = 0; i < arrDir.Length; i++)
{
//不包括temp目录
if (arrDir[i].Name.ToLower() != "temp")
GetDirectory(arrDir[i]);
}
#endregion
}
catch
{
}
}
#endregion
#region === 获取符合XSLT样式的的xml节点字符串 ===
/// <summary>
/// 获取符合XSLT样式的的xml节点字符串
/// </summary>
/// <param name="myServiceNode">xml节点</param>
/// <param name="strXsltFullPathFile">XSLT样式</param>
/// <returns>转换后的xml字符串</returns>
private string TransXSLT(XmlNode myServiceNode, string strXsltFullPathFile)
{
#region === 获取符合XSLT样式的的xml节点字符串 ===
string strResult = "";
try
{
string strContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + myServiceNode.OuterXml;
using (XmlReader xmlReader = System.Xml.XmlReader.Create(new System.IO.StringReader(strContent)))
{
// 获取xml文件,或者XmlNode节点
XPathDocument myXPathDocument = new XPathDocument(xmlReader);
// 按XSLT样式转换Xml数据
XslCompiledTransform myXslTransform = new XslCompiledTransform();
// 读取xslt文件
myXslTransform.Load(strXsltFullPathFile);
// 将内容保存到内存
using (MemoryStream ms = new MemoryStream())
{
#region === 将结果写到内存中 ===
XmlTextWriter writer = new XmlTextWriter(ms, null);
// 按XSLT样式转换xml文件,并保存到writer中
myXslTransform.Transform(myXPathDocument, null, writer);
ms.Seek(0, SeekOrigin.Begin);
#endregion
#region === 获取结果 ===
// 将内容的内容转换成StreamReader流
StreamReader stream = new StreamReader(ms);
// 读取符合XSLT格式的数据
strResult = stream.ReadToEnd();
#endregion
}
}
}
catch
{
}
return strResult;
#endregion
}
#endregion
}
===================================================
输出结果:
会修改config/Common.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="Common.xslt"?>
<configuration>
<services>
<service id="Test" fileName="test.xml" filePath="~/config/test.xml" />
<service id="WNMS_KI" fileName="KPI.xml" filePath="~/config/KPI.xml" />
<service id="WNMS_PI" fileName="KPI.xml" filePath="~/config/KPI.xml" />
</services>
</configuration>
===================================================