questions/48574631/edit-a-large-xml-file

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;

    //https://stackoverflow.com/questions/48574631/edit-a-large-xml-file

    class CustomerAliasXmlEditor : XmlStreamingEditor
    {
		// Confirm that the <customer> element is not in any namespace.
		static readonly XNamespace customerNamespace = ""; 
		
        public static void TransformFromTo(string fromFilePath, XmlReaderSettings readerSettings, string toFilePath, XmlWriterSettings writerSettings)
        {
            using (var xmlReader = XmlReader.Create(fromFilePath, readerSettings))
            using (var xmlWriter = XmlWriter.Create(toFilePath, writerSettings))
            {
                new CustomerAliasXmlEditor(xmlReader, xmlWriter).Process();
            }
        }

        public CustomerAliasXmlEditor(XmlReader reader, XmlWriter writer)
            : base(reader, writer, ShouldTransform, Transform)
        {
        }

        static bool ShouldTransform(XmlReader reader)
        {
            return reader.GetElementName() == customerNamespace + "customer";
        }

        static void Transform(XmlReader from, XmlWriter to)
        {
            var customer = XElement.Load(from);
            var alias = customer.Element(customerNamespace + "alias");
            if (alias != null)
            {
                var name = customer.Element(customerNamespace + "name");
                if (name == null)
                {
                    name = new XElement(customerNamespace + "name");
                    customer.Add(name);
                }
                alias.Remove();
                name.Add(alias);
            }
            customer.WriteTo(to);
        }
    }

    public static partial class XmlReaderExtensions
    {
        public static XName GetElementName(this XmlReader reader)
        {
            if (reader == null)
                return null;
            if (reader.NodeType != XmlNodeType.Element)
                return null;
            string localName = reader.Name;
            string uri = reader.NamespaceURI;
            return XName.Get(localName, uri);
        }
    }

    public static class XmlWriterExtensions
    {
        public static void WriteShallowNode(this XmlWriter writer, XmlReader reader)
        {
            // adapted from http://blogs.msdn.com/b/mfussell/archive/2005/02/12/371546.aspx
            if (reader == null)
                throw new ArgumentNullException("reader");

            if (writer == null)
                throw new ArgumentNullException("writer");

            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
                    writer.WriteAttributes(reader, true);
                    if (reader.IsEmptyElement)
                    {
                        writer.WriteEndElement();
                    }
                    break;

                case XmlNodeType.Text:
                    writer.WriteString(reader.Value);
                    break;

                case XmlNodeType.Whitespace:
                case XmlNodeType.SignificantWhitespace:
                    writer.WriteWhitespace(reader.Value);
                    break;

                case XmlNodeType.CDATA:
                    writer.WriteCData(reader.Value);
                    break;

                case XmlNodeType.EntityReference:
                    writer.WriteEntityRef(reader.Name);
                    break;

                case XmlNodeType.XmlDeclaration:
                case XmlNodeType.ProcessingInstruction:
                    writer.WriteProcessingInstruction(reader.Name, reader.Value);
                    break;

                case XmlNodeType.DocumentType:
                    writer.WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
                    break;

                case XmlNodeType.Comment:
                    writer.WriteComment(reader.Value);
                    break;

                case XmlNodeType.EndElement:
                    writer.WriteFullEndElement();
                    break;

                default:
                    System.Diagnostics.Debug.WriteLine("unknown NodeType " + reader.NodeType);
                    break;

            }
        }
    }

    public abstract class XmlStreamingEditorBase
    {
        readonly XmlReader reader;
        readonly XmlWriter writer;
        readonly Predicate<XmlReader> shouldTransform;

        public XmlStreamingEditorBase(XmlReader reader, XmlWriter writer, Predicate<XmlReader> shouldTransform)
        {
            this.reader = reader;
            this.writer = writer;
            this.shouldTransform = shouldTransform;
        }

        protected XmlReader Reader { get { return reader; } }

        protected XmlWriter Writer { get { return writer; } }

        public void Process()
        {
            while (Reader.Read())
            {
                if (Reader.NodeType == XmlNodeType.Element)
                {
                    if (shouldTransform(Reader))
                    {
                        EditCurrentElement();
                        continue;
                    }
                }
                Writer.WriteShallowNode(Reader);
            }
        }

        protected abstract void EditCurrentElement();
    }

    public class XmlStreamingEditor : XmlStreamingEditorBase
    {
        readonly Action<XmlReader, XmlWriter> transform;

        public XmlStreamingEditor(XmlReader reader, XmlWriter writer, Predicate<XmlReader> shouldTransform, Action<XmlReader, XmlWriter> transform)
            : base(reader, writer, shouldTransform)
        {
            this.transform = transform;
        }

        protected override void EditCurrentElement()
        {
            using (var subReader = Reader.ReadSubtree())
            {
                transform(subReader, Writer);
            }
        }
    }

    class TestClass
    {
        public static void Test()
        {
            var readerSettings = new XmlReaderSettings { IgnoreWhitespace = true };
            var writerSettings = new XmlWriterSettings { Indent = true };

            // Test with and without indentation
            var xml1 = Test(GetXml(), readerSettings, writerSettings);
            var xml2 = Test(XDocument.Parse(GetXml()).ToString(SaveOptions.DisableFormatting), readerSettings, writerSettings);

            XNode.DeepEquals(XElement.Parse(xml1), XElement.Parse(xml2));

            Console.WriteLine("\nDone.");
        }

        public static string Test(string xml, XmlReaderSettings readerSettings, XmlWriterSettings writerSettings)
        {
            string fromFileName = "Question48574631_original.xml";
            string toFileName = "Question48574631_edited.xml";

            try
            {
                File.WriteAllText(fromFileName, xml);

                Console.WriteLine("Input XML file {0}: ", fromFileName);
                Console.WriteLine(xml);

                CustomerAliasXmlEditor.TransformFromTo(fromFileName, readerSettings, toFileName, writerSettings);

                Console.WriteLine("\nResults of editing:");
                var allXml = File.ReadAllText(toFileName);
                Console.WriteLine(allXml);
                return allXml;
            }
            finally
            {
                try
                {
                    if (File.Exists(fromFileName))
                        File.Delete(fromFileName);
                }
                catch (Exception)
                {
                }
                try
                {
                    if (File.Exists(toFileName))
                        File.Delete(toFileName);
                }
                catch (Exception)
                {
                }
            }
        }

        static string GetXml()
        {
            var xml = @"<Root>
<Item>
<SubItem>
<customer>
<name><first>Robert</first></name>
<alias>Rob</alias>
</customer>
</SubItem>
</Item>
<Item>
<SubItem>
<customer>
<name><first>Robert</first></name>
<alias>Rob</alias>
</customer>
</SubItem>
</Item>
<Item>
<SubItem>
<customer>
<name><first>Robert</first></name>
<alias>Rob</alias>
</customer>
</SubItem>
</Item>
<Item>
<SubItem>
<customer>
<name><first>Robert</first></name>
<alias>Rob</alias>
</customer>
</SubItem>
</Item>
<Item>
<SubItem>
<customer>
<name><first>Robert</first></name>
<alias>Rob</alias>
</customer>
</SubItem>
</Item>
</Root>";
            return xml;
        }
    }

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }
						
	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Uncaught exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;