开发者

Optimising XDocument to XDocument XSLT

开发者 https://www.devze.com 2022-12-12 21:35 出处:网络
The following code works but is messy and slow. I am transforming an XDocument to another XDocument using XSLT2 with Saxon, adapted using SaxonWrapper:

The following code works but is messy and slow. I am transforming an XDocument to another XDocument using XSLT2 with Saxon, adapted using 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.开发者_JAVA百科Parse(sw.ToString());
    return outputDoc;
}

I realise that the slowness might actually be in the bits I have no control over but are there better ways to do all the switching between XDocument and XmlDocument and usage of writers?


eddiegroves's solution is fine. Except there is a problem that the writer does not get flushed all the time. To prevent this use the following:

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

This ensures that the writer is disposed - and thus flushed - before the output document is returned.


Rather than using strings to create the XDocument you can try passing in an XmlWriter created from the XDocument directly:

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

Other than that, the other slowdowns are probably in the SaxonWrapper itself and it's use of the older XmlDocument - rather than it's speedier cousin.

0

精彩评论

暂无评论...
验证码 换一张
取 消