Transforming large Xml files

 ̄綄美尐妖づ 提交于 2019-12-22 08:48:33

问题


I was using this extension method to transform very large xml files with an xslt.

Unfortunately, I get an OutOfMemoryException on the source.ToString() line.

I realize there must be a better way, I'm just not sure what that would be?

public static XElement Transform(this XElement source, string xslPath, XsltArgumentList arguments)
{
        var doc = new XmlDocument();
        doc.LoadXml(source.ToString());

        var xsl = new XslCompiledTransform();
        xsl.Load(xslPath);

        using (var swDocument = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
        {
            using (var xtw = new XmlTextWriter(swDocument))
            {
                xsl.Transform((doc.CreateNavigator()), arguments, xtw);
                xtw.Flush();
                return XElement.Parse(swDocument.ToString());
            }
        }
}

Thoughts? Solutions? Etc.

UPDATE: Now that this is solved, I have issues with validating the schema! Validating large Xml files


回答1:


Try this:

using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml.Xsl;

static class Extensions
{
    public static XElement Transform(
        this XElement source, string xslPath, XsltArgumentList arguments)
    {
        var xsl = new XslCompiledTransform();
        xsl.Load(xslPath);

        var result = new XDocument();
        using (var writer = result.CreateWriter())
        {
            xsl.Transform(source.CreateNavigator(), arguments, writer);
        }
        return result.Root;
    }
}

BTW, new XmlTextWriter() is deprecated as of .NET 2.0. Use XmlWriter.Create() instead. Same with new XmlTextReader() and XmlReader.Create().




回答2:


For large XML files you can try to use XPathDocument as suggested in Microsoft Knowledge Base article.

XPathDocument srcDoc = new XPathDocument(srcFile);
XslCompiledTransform myXslTransform = new XslCompiledTransform();
myXslTransform.Load(xslFile);
using (XmlWriter destDoc = XmlWriter.Create(destFile))
{
    myXslTransform.Transform(srcDoc, destDoc);
}


来源:https://stackoverflow.com/questions/2884795/transforming-large-xml-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!