XmlDocument.LoadXml(String) 方法


从指定的字符串加载 XML 文档。Loads the XML document from the specified string.

 virtual void LoadXml(System::String ^ xml);
public virtual void LoadXml (string xml);
abstract member LoadXml : string -> unit
override this.LoadXml : string -> unit
Public Overridable Sub LoadXml (xml As String)



包含要加载的 XML 文档的字符串。String containing the XML document to load.


XML 中存在加载或分析错误。There is a load or parse error in the XML. 在这种情况下,该文档保留为空。In this case, the document remains empty.


下面的示例将 XML 加载到 XmlDocument 对象中,并将其保存到文件中。The following example loads XML into an XmlDocument object and saves it out to a file.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
   // Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<item><name>wrench</name></item>" );
   // Add a price element.
   XmlElement^ newElem = doc->CreateElement( "price" );
   newElem->InnerText = "10.95";
   doc->DocumentElement->AppendChild( newElem );
   // Save the document to a file and auto-indent the output.
   XmlTextWriter^ writer = gcnew XmlTextWriter( "data.xml", nullptr );
   writer->Formatting = Formatting::Indented;
   doc->Save( writer );

using System;
using System.Xml;

public class Sample {

  public static void Main() {

    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();

   // Add a price element.
   XmlElement newElem = doc.CreateElement("price");
   newElem.InnerText = "10.95";

   XmlWriterSettings settings = new XmlWriterSettings();
   settings.Indent = true;
   // Save the document to a file and auto-indent the output.
   XmlWriter writer = XmlWriter.Create("data.xml", settings);
Imports System.Xml

public class Sample 

  public shared sub Main() 
    ' Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()

   ' Add a price element.
   Dim newElem as XmlElement = doc.CreateElement("price")
   newElem.InnerText = "10.95"

   Dim settings As New XmlWriterSettings()
   settings.Indent = True
   ' Save the document to a file and auto-indent the output.
   Dim writer As XmlWriter = XmlWriter.Create("data.xml", settings)
  end sub
end class


默认情况下,该 LoadXml 方法不保留空格或有效空白。By default the LoadXml method does not preserve white space or significant white space.

此方法解析 Dtd,但不执行 DTD 或架构验证。This method parses DTDs, but does not do DTD or Schema validation. 如果要进行验证,可以 XmlReader 使用 XmlReaderSettings 类和方法创建验证实例 CreateIf you want validation to occur, you can create a validating XmlReader instance by using the XmlReaderSettings class and the Create method. 有关详细信息,请参阅 XmlReader 引用页的“备注”部分。For more information, see the Remarks section of the XmlReader reference page.

如果要从、、或加载,请 Stream String TextReader XmlReader 使用 load 方法,而不是使用此方法。If you want to load from a Stream, String, TextReader, or XmlReader, use the Load method instead of this method.

此方法是文档对象模型 (DOM) 的 Microsoft 扩展。This method is a Microsoft extension to the Document Object Model (DOM).