XmlDocument.LoadXml(String) 方法

定义

从指定的字符串加载 XML 文档。

public:
 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

包含要加载的 XML 文档的字符串。

例外

XML 中存在加载或分析错误。 在这种情况下,文档保持为空。

示例

以下示例将 XML 加载到对象 XmlDocument 中,并将其保存到文件中。

using System;
using System.Xml;

public class Sample {

  public static void Main() {

    // Create the XmlDocument.
    XmlDocument doc = new 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);

   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);
    doc.Save(writer);
  }
}
Imports System.Xml

public class Sample 

  public shared sub Main() 
 
    ' Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    doc.LoadXml("<item><name>wrench</name></item>")

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

   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)
    doc.Save(writer)
  end sub
end class

注解

默认情况下, LoadXml 该方法不会保留空格或重要的空白。

此方法分析文档类型定义(DTD),但不执行 DTD 或架构验证。 如果要进行验证,可以使用类和XmlReader方法创建验证XmlReaderSettings实例Create。 有关详细信息,请参阅 XmlReader 引用页的“备注”部分。

如果要从 StreamStringTextReaderXmlReader使用 Load 方法而不是此方法进行加载。

此方法是文档对象模型(DOM)的Microsoft扩展。

适用于

另请参阅