优化XDocument到XDocument XSLT

3
以下代码可以工作,但是很混乱而且速度慢。 我正在使用Saxon的XSLT2将XDocument转换为另一个XDocument,并使用SaxonWrapper进行适应:
public static XDocument HSRTransform(XDocument source)
{
    System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
    System.IO.Stream xslfile = thisExe.GetManifestResourceStream("C2KDataTransform.Resources.hsr.xsl");

    XmlDocument xslDoc = new XmlDocument();
    xslDoc.Load(xslfile);

    XmlDocument sourceDoc = new XmlDocument();
    sourceDoc.Load(source.CreateReader());

    var sw = new StringWriter();

    Xsl2Processor processor = new Xsl2Processor();
    processor.Load(xslDoc);

    processor.Transform(sourceDoc, new XmlTextWriter(sw));

    XDocument outputDoc = XDocument.Parse(sw.ToString());
    return outputDoc;
}

我意识到速度慢可能实际上是在我无法控制的部分,但是是否有更好的方法来处理XDocument和XmlDocument之间的所有切换以及写入器的使用?

2个回答

5

eddiegroves的解决方案很好。但是有一个问题,就是写入器并不总是被刷新。为了避免这种情况,请使用以下方法:

XDocument outputDoc = new XDocument();
using (var writer = outputDoc.CreateWriter()) {
    processor.Transform(sourceDoc, writer);
}
return outputDoc;

这样可以确保写入器被处理 - 从而被清空 - 在输出文档返回之前。

3

不要使用字符串来创建XDocument,你可以尝试直接传入从XDocument创建的XmlWriter:

XDocument outputDoc = new XDocument();
processor.Transform(sourceDoc, outputDoc.CreateWriter());
return outputDoc;

除此之外,其他的减速可能在SaxonWrapper本身和它使用的旧XmlDocument上,而不是更快的表兄。


谢谢 - 这样整洁漂亮。 - djskinner
1
@Devela XDocument和Linq to XML是.NET BCL中现代的XML API,对于大多数情况来说,它们可以替代XmlDocuemnt。 - Eddie Groves

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接