¿Cómo puedo detener el cierre automático de elementos XML vacíos usando XmlDocument en C #?

Antes de que la gente me llame la atención diciendo que el analizador XML no debería importarme si los elementos están vacíos o se cierran automáticamente, hay una razón por la que no puedo permitir elementos XML con cierre automático. La razón es que en realidad estoy trabajando con SGML, no con XML, y el DTD de SGML con el que estoy trabajando es muy estricto y no lo permite.

Lo que tengo son varios miles de archivos SGML en los que he necesitado ejecutar XSLT. Por lo tanto, tuve que convertir el SGML a XML temporalmente para aplicar el XSLT. Luego escribí un método que los convierte de nuevo a SGML (esencialmente solo reemplazando la declaración XML con la declaración SGML y escribiendo cualquier otra declaración de entidad, como entidades gráficas).

Mi problema es que después de esta conversión de nuevo a SGML, cuando abro los archivos en mi editor de SGML, los archivos no se analizan ya que los elementos vacíos se han cerrado automáticamente.

¿Alguien sabe cómo puedo evitar que esto suceda cuando uso XmlDocument?

Los métodos que convierten el SGML a XML y viceversa se muestran a continuación.

//converts the SGML file to XML – it’s during this conversion that the 
//empty elements get self-closed, i think

private XmlDocument convertToXML(TextReader reader)
        {
            // setup SgmlReader
            Sgml.SgmlReader sgmlReader = new Sgml.SgmlReader();
            //sgmlReader.DocType = "HTML";
            sgmlReader.WhitespaceHandling = WhitespaceHandling.All;
            sgmlReader.CaseFolding = Sgml.CaseFolding.ToLower;
            sgmlReader.InputStream = reader;


            // create document
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;

            doc.XmlResolver = null;
            doc.Load(sgmlReader);
            return doc;
        }

// method to apply the XSLT stylesheet to the XML document

private void filterApplic(string applicFilter)
        {
            string stylesheet = getRequiredStylesheet(); // do this just once

            if (stylesheet != "")
            {
                foreach (string file in FilesToConvert)
                {
                    fileName = Path.GetFileName(file); //gets just the file name from the path
                    fileNameNoExt = Path.GetFileNameWithoutExtension(file);
                    string ext = Path.GetExtension(file);

                    if (ext == ".sgm")
                    {
                        try
                        {
                            publicIdentifier = getDoctype(file); // gets the sgml declaration
                            entitiesList = getEntitites(file); // gets the list of entities

                            TextReader tr = new StreamReader(file);
                            myDoc = convertToXML(tr);

                            myDoc.Save(outputFolder + "\\temp.xml");

                            var myXslTrans = new XslCompiledTransform();

                            myXslTrans.Load(stylesheet);
                            myXslTrans.Transform(outputFolder + "\\temp.xml", Path.Combine(outputFolder, fileNameNoExt +".xml"));

                            XmlDocument convertedDoc = new XmlDocument();
                           convertedDoc.Load(Path.Combine(outputFolder, fileNameNoExt + ".xml"));

                            convertToSGM(convertedDoc);

                            filesTransformed++;
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.ToString());
                        }

                    }
                }
            }
            else
            {
                MessageBox.Show("The stylesheet was retured empty. Cannot perform Applicability filter.");
                return;
            }


            MessageBox.Show("Complete! " + filesTransformed.ToString() + " files filtered for " + applicFilter);
        }


//convert files back to SGML
private void convertToSGM(XmlDocument myDoc)
        {

            using (var stringWriter = new StringWriter())
            using (var xmlTextWriter = XmlWriter.Create(stringWriter, settings))
            {

                myDoc.WriteTo(xmlTextWriter);
                xmlTextWriter.Flush();


                string xmltext = stringWriter.GetStringBuilder().ToString();

                xmltext = xmltext.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<!DOCTYPE DMODULE " + publicIdentifier + ">");
                xmltext = xmltext.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "<!DOCTYPE DMODULE " + publicIdentifier + ">");

                if (entitiesList.Count != 0)
                {
                    string entityListAsOne = "";

                    foreach (string entity in entitiesList)
                    {
                        entityListAsOne = entityListAsOne + "\r\n" + entity;
                    }

                    xmltext = xmltext.Replace("//EN\">", "//EN\" [" + entityListAsOne + "]>");
                }

                File.WriteAllText(Path.Combine(outputFolder, fileNameNoExt + ".sgm"), xmltext);
            }


        }

Respuestas a la pregunta(1)

Su respuesta a la pregunta