保存和写出文档

加载并保存 XmlDocument 后,保存的文档在下列方面可能不同于原始文档:

  • 如果在调用 Save 方法之间将 PreserveWhitespace 属性设置为 true,文档中的空白在输出中将保留;如果此属性为 false,XmlDocument 将使输出自动缩进。

  • 各个属性之间的所有空白都缩减为一个空白字符。

  • 更改元素间的空白。 保留有效空白,但不保留无效空白。 但是在文档保存后,默认情况下将使用 XmlTextWriter Indenting 模式实现整洁的输出,使文档更加易读。

  • 属性值两边所用的引号字符在默认情况下更改为双引号。 可以使用 XmlTextWriterQuoteChar 属性将引号字符设置为双引号或单引号。

  • 默认情况下,扩展像 { 这样的数字字符实体。

  • 不保留输入文档中的字节顺序标记。 除非显式创建指定不同编码的 XML 声明,否则 UCS-2 保存为 UTF-8。

  • 如果要将 XmlDocument 写出到文件或流中,则写出的输出与文档内容相同。 也就是说,仅当文档中包含 XmlDeclaration 时才写出 XmlDeclaration,并且写出文档时所使用的编码与声明节点中给定的编码相同。

写出 XmlDeclaration

OuterXmlInnerXmlWriteToXmlDocumentXmlDeclaration 成员与 SaveWriteContentToXmlDocument 方法共同创建 XML 声明。

对于 OuterXmlXmlDocument 属性、InnerXml 以及 SaveWriteToWriteContentTo 方法,在 XML 声明中写出的编码从 XmlDeclaration 节点获取。 如果没有 XmlDeclaration 节点,则不会写出 XmlDeclaration。 如果 XmlDeclaration 节点中没有编码,则不会在 XML 声明中写出编码。

XmlDocument.SaveXmlDocument.Save 方法始终写出 XmlDeclaration。 这些方法从其写入的编写器中获取编码。 也就是说,编写器的编码值重写文档和 XmlDeclaration 对象的编码。 例如,下列代码不在输出文件 out.xml 中的 XML 声明中写出编码。

Dim doc As New XmlDocument()
Dim tw As XmlTextWriter = New XmlTextWriter("out.xml", Nothing)
doc.Load("text.xml")
doc.Save(tw)
XmlDocument doc = new XmlDocument();
XmlTextWriter tw = new XmlTextWriter("out.xml", null);
doc.Load("text.xml");
doc.Save(tw);

对于 Save 方法,XML 声明使用 XmlWriter 类中的 WriteStartDocument 方法写出。 因此,重写 WriteStartDocument 方法将更改如何编写文档的开头。

对于 OuterXmlWriteToInnerXmlXmlDeclaration 成员,如果 Encoding 属性未设置,将不会写出任何编码。 否则,在 XML 声明中写出的编码与 Encoding 属性中的编码相同。

用 OuterXml 属性写出文档内容

OuterXml 属性是 Microsoft 对万维网联合会 (W3C) XML 文档对象模型 (DOM) 标准的扩展。 OuterXml 属性用于获取整个 XML 文档的标记,或者只获取单个节点及其子节点的标记。 OuterXml 返回表示给定节点及其所有子节点的标记。

下面的代码示例显示了如何将整个文档保存为一个字符串。

Dim mydoc As New XmlDocument()
' Perform application needs here, like mydoc.Load("myfile");
' Now save the entire document to a string variable called "xml".
Dim xml As String = mydoc.OuterXml
XmlDocument mydoc = new XmlDocument();
// Perform application needs here, like mydoc.Load("myfile");
// Now save the entire document to a string variable called "xml".
string xml = mydoc.OuterXml;

下面的代码示例显示了如何只保存文档元素。

' For the content of the Document Element only.
Dim xml As String = mydoc.DocumentElement.OuterXml
// For the content of the Document Element only.
string xml = mydoc.DocumentElement.OuterXml;

与此相反,如果您需要子节点的内容,可以使用 InnerText 属性。

请参见

概念

XML 文档对象模型 (DOM)