程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> 在ASP.net中的XML操作筆記

在ASP.net中的XML操作筆記

編輯:關於ASP.NET

前幾天一老鳥跑來說:“小Q,看來這幾天你沒有什麼事情,來給你安排一下工作!”我曰:“哦”,~~~。從此就開始餓補.net中操作XML的東東。好了,廢話不說,做先!

下面是的代碼是XML的模板TestTemplate.vxml

1
2
3
4
5
6
7
8 此值小於9
9
10
11 此值大於2
12
13
14
15

在這個模板中保存的是VoiceXML文件,這是用來制定語音流程的東東,通過它您就能夠實現類似10086或118114的語音台的功能。(VoiceXML小弟正在學習,以後會寫些相關的隨筆。)

下面的這行代碼就是Vxml.aspx中的內容。注意:必須要將除下面這行代碼之外的所有內容刪除,只有這樣才能以流的方式輸出來。

1

汗顏,就為了前面的這行代碼我整整浪費了一個下午,郁悶!

下面的這行代碼就是我今天的成果,它的名字就叫“Vxml.aspx.cs”!哈哈~~“呆,罵規罵,別打呀!~~~救命呀!-----咚”。(從桌子下爬了起來,)。在這裡必須要應用兩個庫,就是System.IO;和System.Xml。具體的執行過程是:先讀取TestTemplate.vxml;然後,替換模板中相關節點屬性的值“val”為“老鼠”;再後,在form節點的最後部分加入<老鼠 zizi="……">……;最後,在本頁輸出結果。

1using System;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5using System.Web;
6using System.Web.Security;
7using System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.IO;
12using System.Xml;
13public partial class Vxml_Vxml : System.Web.UI.Page
14{
15 protected void Page_Load(object sender, EventArgs e)
16 {
17 Response.Clear();
18 string path = Server.MapPath("TestTemplate.vxml");
19 //DOM方式讀取
20 XmlDocument doc = new XmlDocument();//建立XML文件對象
21 doc.Load(path);//讀取xml文件
22 XmlElement objElement = doc.DocumentElement;//獲取XML文件的根元素
23 foreach (XmlNode test in objElement.ChildNodes)
24 {
25 if (test.Name == "form")//找到名稱為form的節點
26 {
27 foreach (XmlNode test1 in test.ChildNodes)//在form節點中便利節點
28 {//找到在“form”子節點中屬性“name”的值為"val"的節點。
29 if (test1.Attributes.Count > 0 && test1.Attributes["name"].InnerXml == "val")
30 {
31 test1.Attributes["name"].InnerXml = "老鼠";//設置name屬性的值為“老鼠”
32 }
33 else if (test1.Name == "block")//找到“block”節點
34 {
35 foreach (XmlNode test2 in test1.ChildNodes)
36 {//將“block”節點的所以子節點屬性“cond”中的“Val”替換成“老鼠”。
37 if (test2.Attributes["cond"].InnerXml.Contains("val"))
38 {
39 string str = test2.Attributes["cond"].InnerXml;
40 str = "老鼠" + str.Substring(3);//不能用“Replace”真是郁悶
41 test2.Attributes["cond"].InnerXml = str;
42 }
43 }
44 }
45 }
46 XmlElement node = doc.CreateElement("老鼠");//建立“老鼠”節點
47 XmlAttribute attribute = doc.CreateAttribute("zizi");
48 node.SetAttributeNode(attribute);
49 node.SetAttribute("zizi", "……");
50 test.AppendChild(node);
51 node.InnerXml = "……";
52 test.InsertBefore(node, test.LastChild);//將新建的“老鼠”節點給“form”
53 doc.Save(Response.OutputStream);//將修改後的xml文件以流的方式輸出到當前頁面。
54 }
55 }
56 }
57}
58

看看,這就是結果。

1
2
3
4
5
6
7
8 此值小於9
9
10
11 此值大於2
12
13
14 <老鼠 zizi="……">……
15
16

好了,寫完了,真累!哦,下班了!走。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved