C #调用XML 文件
C# 调用XML 文件简单实例
需要引用XML 命名 using System.Xml;
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace Wingtech.CSharpSample.XmlSample { public partial class Display : Form { public Display() { InitializeComponent(); } private void btnReadXML_Click(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); try { doc.Load(@"..\..\SampleXml.xml"); } catch { MessageBox.Show("XML 文件加载错误!"); } XmlNodeList elemetList1 = doc.GetElementsByTagName("server"); for (int i = 0; i < elemetList1.Count; i++) { txtName.Text = elemetList1.Item(i).InnerText; } XmlNodeList elementList2 = doc.GetElementsByTagName("user"); for(int j=0;j<elementList2.Count;j++) { txtPrice.Text = elementList2.Item(j).InnerXml; } XmlNodeList elementList3 = doc.GetElementsByTagName("pass"); for (int j = 0; j < elementList3.Count; j++) { txtPass.Text = elementList3.Item(j).InnerXml; } } } }
XML 实例 SampleXml.xml
<?xml version="1.0" encoding="utf-8" ?> <merchandise> <server>Pen</server> <user>$0.4</user> <pass>HP</pass> </merchandise>
结果