開發過程中我們會遇到一些讀取xml文件的時候,下面是我學習的整理。
用XmlDocument讀取加載
XmlDocument doc = new XmlDocument();
doc.Load("XML.xml");//xml的文件路徑
//獲取到XML的根元素進行操作
XmlNodeList xn = doc.SelectNodes("countries/country");
完整代碼如下
前端:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="demo0427.aspx.cs" Inherits="WebApplication2.demo0427" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>xml加載到tree中</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<Nodes>
<asp:TreeNode Text="跟節點" Value="跟節點">
<asp:TreeNode Text="子節點1" Value="子節點1"></asp:TreeNode>
<asp:TreeNode Text="子節點2" Value="子節點2"></asp:TreeNode>
</asp:TreeNode>
</Nodes>
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px" NodeSpacing="0px" VerticalPadding="2px" />
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
</div>
</form>
</body>
</html>
后端:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
namespace WebApplication2
{
public partial class demo0427 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string path3 = Server.MapPath("/");//獲得當前的路徑
//將XML文件加載進來
XmlDocument doc = new XmlDocument();
doc.Load("" + path3 + "XML.xml");
//獲取到XML的根元素進行操作
XmlNodeList xn = doc.SelectNodes("countries/country");
foreach (XmlNode xn1 in xn)
{ //獲取第一個元素text的值
string text = xn1.FirstChild.InnerXml;
XmlNode v = xn1.SelectSingleNode("value");
string re = v.InnerText;
//獲取屬性值
string val = v.Attributes["id"].Value;
Console.WriteLine(text + ":" + val + ":" + re);
//第一級樹
TreeNode trerotnod = new TreeNode();
//第二級樹
TreeNode x = new TreeNode();
TreeNode y = new TreeNode();
trerotnod.Text = xn1.InnerText;
y.Text = val;
x.Text = re;
//把第二級的樹添加到第一級的樹中
trerotnod.ChildNodes.Add(x);
trerotnod.ChildNodes.Add(y);
TreeView1.Nodes.Add(trerotnod);
}
}
}
}
}
