Remove docType declaration from XmlSchema.net output

The following code:

        XmlSchema xmlSchema = new XmlSchema();

        XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();            
        xmlSchemaElement.Name = "SomeElement";
        xmlSchema.Items.Add(xmlSchemaElement);

        XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
        xmlNamespaceManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

        StringWriter stringWriter = new StringWriter();            
        xmlSchema.Write(stringWriter, xmlNamespaceManager);

        String result = stringWriter.ToString();

Gives me:

<?xml version="1.0" encoding="utf-16"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="SomeElement" /> </xs:schema>

I do not need a docType declaration.

Obviously, I could just delete the first line. But does anyone know of a way to stop the XmlSchema class from writing the docType declaration first?

+3
source share
1 answer

Instead of writing directly on StringWriter, write to XmlWriter. This way you can set certain serialization options.

StringWriter stringWriter = new StringWriter();

XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; // <-- this is what you care about
XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings);
xmlSchema.Write(xmlWriter, xmlNamespaceManager);

String result = stringWriter.ToString();
+4
source

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


All Articles