Convert Large Xml Files

I used this extension method to convert very large xml files using xslt.

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

I understand that there must be a better way, I'm just not sure what it will 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 resolved, I have problems checking the circuit! Validating Large Xml Files

+4
source share
2 answers

Try the following:

 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() deprecated from .NET 2.0. Use XmlWriter.Create() instead. Same thing with new XmlTextReader() and XmlReader.Create() .

+8
source

For large XML files, you can try using XPathDocument, as suggested in the 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); } 
+1
source

Source: https://habr.com/ru/post/1310553/


All Articles