共用方式為


HOW TO:從檔案讀取 XML

更新:2007 年 11 月

這個範例會使用 XmlTextReader 類別,從範例檔案中擷取項目名稱和文字字串,並將資訊儲存在字串變數中。

範例

System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\IntroToVCS.xml");
            string contents = "";
            while (reader.Read()) 
            {
                reader.MoveToContent();
                if (reader.NodeType == System.Xml.XmlNodeType.Element)
                    contents += "<"+reader.Name + ">\n";
                if (reader.NodeType == System.Xml.XmlNodeType.Text)
                    contents += reader.Value + "\n";
            }
            System.Console.Write(contents);

編譯程式碼

複製程式碼,並貼至主控台應用程式的 Main 方法中。

請使用實際檔名取代 "c:\\IntroToVCS.xml"。

注意事項:

XML 文件必須是語式正確 (Well-Formed)。

穩固程式設計

以下情形可能會導致例外狀況:

  • 路徑名稱可能太長。

請參閱

概念

在 Visual C# 中設計使用者介面

其他資源

存取以及顯示資料

Visual C# 導覽