Создание большого XML-файла XmlWriter с разделением на методы

Я создаю большой XML-файл с помощью XmlWriter и знаю, что с помощью

             using (XmlWriter writer = XmlWriter.Create("file.xml", settings))
        {

            writer.WriteStartElement("Research", "http://www.rixml.org/2013/2/RIXML");
            writer.WriteAttributeString("xmlns", "rixmldt", null, "http://www.rixml.org/2013/2/RIXML-datatypes");
            writer.WriteAttributeString("xsi", "schemaLocation", null, "http://www.rixml.org/2013/2/RIXML");
            //dropdown selection for reseach id?
            writer.WriteAttributeString("researchID", "BOGUS ID");
            writer.WriteAttributeString("language", "eng");
            //fix date time
            writer.WriteAttributeString("createdDateTime", System.DateTime.Now.Date.ToString());
            writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
            writer.WriteStartElement("Product");
            //dropdown selection for prioduct id?
            writer.WriteAttributeString("productID", "asdf");
            //status info
            writer.WriteStartElement("StatusInfo");

            writer.WriteAttributeString("currentStatusIndicatior", "Yes");
            writer.WriteAttributeString("statusDateTime", System.DateTime.Now.Date.ToString());
            writer.WriteAttributeString("statusType", "Published");
            writer.WriteEndElement();
            writer.WriteStartElement("Source");
            writer.WriteStartElement("Organization");
            //organization info
            writer.WriteAttributeString("type", "SellSideFirm");
            writer.WriteAttributeString("primaryIndicatior", "Yes");
            //organization1
            writer.WriteStartElement("OrganizationID");
            writer.WriteAttributeString("idType", "Bloomberg");
            writer.WriteString("1234");
            writer.WriteEndElement();
            //org 2
            writer.WriteStartElement("OrganizationID");
            writer.WriteAttributeString("idType", "FactSet");
            writer.WriteString("rep_example");
            writer.WriteEndElement();
....
            writer.WriteEndElement();
            writer.Flush();
}

Считается самым быстрым способом создания большого файла, но я не могу найти, чтобы кто-нибудь говорил (или в документах XmlWriter) о разделении всего этого на методы, которые генерируют фрагменты xml. Мой метод составляет около 150 строк, и я хотел бы сохранить его как можно более модульным, поскольку все заполняемые данные будут в основном извлечены из формы. Это означает, что метод, в котором находится этот оператор, также будет иметь массу аргументов.

Возможно ли что-то подобное без использования файлового потока или локального сохранения данных ради модульности / организации? Или это просто замедлит его?


person Kevin Young    schedule 27.06.2017    source источник
comment
Наличие методов для разных частей не имеет большого значения. Эта единственная строка не дает много информации о том, как вы на самом деле пишете что-то или как бы вы их разбили.   -  person Sami Kuhmonen    schedule 27.06.2017
comment
@SamiKuhmonen Я добавил большую часть (не все) того, что происходит внутри этой строки. Конечно, есть такие области, как организации, для которых я мог бы использовать цикл, но я просто пытаюсь оценить свои возможности.   -  person Kevin Young    schedule 27.06.2017
comment
Вы можете легко разделить их на методы и, если хотите, просто дать автору в качестве аргумента. Это не сделает его медленнее, и, если станет яснее, это хорошее изменение.   -  person Sami Kuhmonen    schedule 27.06.2017
comment
@SamiKuhmonen спасибо, это именно то, что я хотел услышать :)   -  person Kevin Young    schedule 27.06.2017


Ответы (1)


Мне нравится приведенный ниже код немного больше, чем ваш, потому что он лучше организован, легче читается и вам не нужно добавлять конечные элементы.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            string header = "<Research xmlns=\"http://www.rixml.org/2013/2/RIXML\"" +
                                              " xmlns:rixmldt=\"http://www.rixml.org/2013/2/RIXML-datatypes\"" +
                                              " xmlns:xsi=\"http://www.rixml.org/2013/2/RIXML\"" +
                                              " researchID=\"BOGUS ID\"" +
                                              " language=\"eng\"" +
                                              " createdDateTime=\"" + System.DateTime.Now.Date.ToString() + "\"" +
                                              " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";


            using (XmlWriter writer = XmlWriter.Create(FILENAME, settings))
            {
                writer.WriteRaw(header) ;

                XElement product = new XElement("Product", new XAttribute("productID", "asdf"));

                XElement statusInfo = new XElement("StatusInfo", new object[] {
                        new XAttribute("currentStatusIndicatior", "Yes"),
                        new XAttribute("statusDateTime", System.DateTime.Now.Date.ToString()),
                        new XAttribute("statusType", "Published")
                });
                product.Add(statusInfo);

                XElement source = new XElement("Source", new object[] {
                    new XElement("Organization", new object[] {
                        new XAttribute("type", "SellSideFirm"),
                        new XAttribute("primaryIndicatior", "Yes"),
                        new XElement("OrganizationID", new object[] {
                            new XAttribute("idType", "Bloomberg"),
                            "1234"
                        })
                    })
                });
                product.Add(source);

                XElement organizationID = new XElement("OrganizationID", new object[] {
                    new XAttribute("idType", "FactSet"),
                    "rep_example"
                });
                product.Add(organizationID);

                product.WriteTo(writer);

                writer.Flush();
                writer.Close();
            }
        }
    }
}
person jdweng    schedule 27.06.2017