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 或 Schema 驗證。 如果你想讓驗證發生,你可以用XmlReader類別和XmlReaderSettings方法建立驗證Create實例。 如需詳細資訊,請參閱 XmlReader 參考頁面的<備註>一節。

如果你想從 StreamStringTextReaderXmlReader載入,請使用 Load 方法代替此方法。

此方法是 Microsoft 對文件物件模型(DOM)的擴充。

適用於

另請參閱