我有一个带2个参数的函数:1 = XML文件,2 = XSLT文件,然后执行转换并返回生成的HTML。
这是功能:
/// <summary>
/// Will apply an XSLT style to any XML file and return the rendered HTML.
/// </summary>
/// <param name="xmlFileName">
/// The file name of the XML document.
/// </param>
/// <param name="xslFileName">
/// The file name of the XSL document.
/// </param>
/// <returns>
/// The rendered HTML.
/// </returns>
public string TransformXml(string xmlFileName, string xslFileName)
{
var xtr = new XmlTextReader(xmlFileName)
{
WhitespaceHandling = WhitespaceHandling.None
};
var xd = new XmlDocument();
xd.Load(xtr);
var xslt = new System.Xml.Xsl.XslCompiledTransform();
xslt.Load(xslFileName);
var stm = new MemoryStream();
xslt.Transform(xd, null, stm);
stm.Position = 1;
var sr = new StreamReader(stm);
xtr.Close();
return sr.ReadToEnd();
}
我想更改函数不接受XML的文件,而只是一个对象。 该对象与xslt完全兼容,如果它被序列化为文件。但我不想首先将它序列化为文件。
所以回顾一下:保持xslt来自文件,但xml输入应该是我传递的对象,并且希望在没有任何文件系统交互的情况下生成xml。
答案 0 :(得分:9)
您可以将对象序列化为字符串,将字符串加载到XmlDocument
,然后执行转换:
public string TransformXml(object data, string xslFileName)
{
XmlSerializer xs = new XmlSerializer(data.GetType());
string xmlString;
using (StringWriter swr = new StringWriter())
{
xs.Serialize(swr, data);
xmlString = swr.ToString();
}
var xd = new XmlDocument();
xd.LoadXml(xmlString);
var xslt = new System.Xml.Xsl.XslCompiledTransform();
xslt.Load(xslFileName);
var stm = new MemoryStream();
xslt.Transform(xd, null, stm);
stm.Position = 0;
var sr = new StreamReader(stm);
return sr.ReadToEnd();
}
答案 1 :(得分:3)
这是一个将对象转换为XDocument的函数(如果你还没有使用XDocument,可以为XmlDocument更改它)。当然,如果对象不可序列化,这将抛出异常。
public static XDocument ConvertToXml<T>(this T o)
{
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer,o);
StringReader reader = new StringReader(builder.ToString());
return XDocument.Load(reader);
}
,这是XmlDocument的一个
public static XmlDocument ConvertToXml<T>(this T o)
{
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer,o);
StringReader reader = new StringReader(builder.ToString());
XmlDocument doc = new XmlDocument();
doc.Load(reader);
return doc;
}
答案 2 :(得分:1)
未经过测试,但您可以使用XPathDocument获取Stream,并且由于XPathDocument实现了IXPathNavigable,因此可以将其用于转换:
public string TransformXml(Stream xmlFile, string xslFileName)
{
var doc = new XPathDocument(xmlFile);
var xslt = new System.Xml.Xsl.XslCompiledTransform();
xslt.Load(xslFileName);
var stm = new MemoryStream();
xslt.Transform(doc, null, stm);
stm.Position = 1;
var sr = new StreamReader(stm);
return sr.ReadToEnd();
}
答案 3 :(得分:0)
查看this article,其中描述了创建一个XPathNavigator
,它可以导航对象图的属性,这是一个非常强大的XPath和XSLT组合。