开发者

Remove docType declaration from output of XmlSchema .net

The following code:

        XmlSchema xmlSchema = new XmlSchema();

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

        XmlNamespaceMan开发者_JS百科ager 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 don't want the docType declaration.

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


Instead of writing directly to your StringWriter, write to an XmlWriter. That way, you can set specific 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜