从XmlSchema .net的输出中删除docType声明

时间:2010-11-09 17:14:51

标签: .net xml doctype

以下代码:

        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();

给我:

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

我不想要docType声明。

显然我可以删除第一行。但是,有没有人知道一种方法来阻止XmlSchema类首先编写docType声明?

1 个答案:

答案 0 :(得分:4)

不要直接写入StringWriter,而是写信给XmlWriter。这样,您可以设置特定的序列化选项。

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();