我正在寻找更好的解决方案来读取服务器端 xslt 并转换为 xml。它工作正常,但正在寻找更好的灵魂……谢谢您的提前帮助。
- XML 内容作为字符串传递,
- 使用 HttpWebRequest 获取服务器端 XSLT
获取字符串作为输出。
string xsltUrl = "http://aaa.bbb.com/ddd/eee/JY_test.xslt"; string outputXML = Common.Display("en", xmlText, xsltUrl); Label1.Text = outputXML;
私有静态 XElement rawMenu;
public static string Display(string lang, string xml, string xsltUrl)
{
rawMenu = XElement.Parse(xml);
return rawMenu.TransformXSLT(xsltUrl, lang);
}
public string TransformXSLT(XElement results, string xsltUrl, string Lang)
{
//variables
var strm = new MemoryStream();
var settings = new XmlWriterSettings();
//tell the stream that it will be creating a xml fragment and not a full document.
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.Encoding = Encoding.UTF8;
settings.CloseOutput = false;
//pass in the lang of the page
if (string.IsNullOrWhiteSpace(Lang)) //set a default just in case.
Lang = "en";
XsltArgumentList argsList = new XsltArgumentList();
argsList.AddParam("CurrentLang", "", Lang);
//// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
try
{
var stream = HttpWebRequest.Create(xsltUrl) as HttpWebRequest;
stream.Method = "GET";
stream.ContentType = "text/xml; encoding='utf-8'";
using (HttpWebResponse response = stream.GetResponse() as HttpWebResponse)
{
Stream resStream = response.GetResponseStream();
//Create the reader to load the stylesheet.
using (XmlReader xmlReader = XmlReader.Create(resStream))
{
xslt.Load(xmlReader);
}
using (MemoryStream ms = new MemoryStream())
{
XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8);
xslt.Transform(results.CreateReader(), argsList, writer);
ms.Position = 0;
using (StreamReader rd = new StreamReader(ms))
{
var strHtml = rd.ReadToEnd();
return strHtml;
}
}
}
}
catch (WebException ex)
{
if (ex.Response is HttpWebResponse)
{
switch (((HttpWebResponse)ex.Response).StatusCode)
{
case HttpStatusCode.NotFound:
throw new ApplicationException(((HttpWebResponse)ex.Response).StatusDescription);
default:
throw ex;
}
}
throw;
}
}