about 6 years ago

一.大綱
目前工作上常見XML交換資料的技術應用,為使大家能夠有效的使用XML開發各項技術需求,因此設計此一次課程。

學習目標 :

a. 對於XML技術有基礎的了解
b. 利用ASP進行XML資料的傳輸與接收
c. 利用JavaScript進行XML資料的傳輸與接收
d. 利用Asp.NET進行XML資料的傳輸與接收

二.什麼是XML? HTML? XHTML?

What’s XML
• XML stands for EXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to carry data, not to display data
• XML tags are not predefined. You must define your own tags
• XML is designed to be self-descriptive
• XML is a W3C Recommendation

HTML與XML的差異
• XML was designed to transport and store data, with focus on what data is
• HTML was designed to display data, with focus on how data looks
XHTML與HTML的差異

1.Document Structure
• XHTML DOCTYPE is mandatory
• The XML namespace attribute in is mandatory
• ,

, , and is mandatory
2.XHTML Elements
• XHTML elements must be properly nested
• XHTML elements must always be closed
• XHTML elements must be in lowercase
• XHTML documents must have one root element
3.XHTML Attributes
• Attribute names must be in lower case
• Attribute values must be quoted
• Attribute minimization is forbidden

參考資料: http://www.w3schools.com/xml/xml_whatis.asp
http://www.w3schools.com/html/html_xhtml.asp

三.如何利用ASP傳送與接收XML

設計一隻檔案XMLSend.asp

XMLSend.asp
<%
    
    '//================測試XML傳送資料================
    url="http://10.10.1.12/jackli/XMLReader.asp" '處理位置
    
    '//================使用FSO來處理開啟xml檔案 並讀取XML內容================
    Set fs = Server.CreateObject("Scripting.FileSystemObject")
    file_Path = Server.MapPath("User.xml")
    Const ForReading = 1, ForWriting = 2, ForAppending = 8 'Source MSDN
    Set XmlContent = fs.OpenTextFile( file_Path ,ForReading )
    
    xml = XmlContent.ReadAll    'xml檔案中的內容 other : XmlContent.Read(4) 讀取第幾行 XmlContent.ReadLine 
    XmlContent.close()
    set fs = nothing
    
    '//==============連結到對應的位置,並傳送XML==============================
    Set oHttpPost = CreateObject("Microsoft.XMLHTTP") 
    oHttpPost.Open "POST", url, False 
    oHttpPost.Send xml
    '//取得回傳的值(Text,XML,HTML....隨程式設計師設計而論
    strRetXML = oHttpPost.responseText
    
    '//取得回來的值 需要經過文字串流,將文字轉回成自己所需要顯示的編碼格式
    dim objstream  
    set objstream = Server.CreateObject("adodb.stream") 
    objstream.Type = 1  'Write
    objstream.Mode =3  
    objstream.Open  
    objstream.Write oHttpPost.responseBody '寫入  
    objstream.Position = 0  '現在位置
    objstream.Type = 2  'read 
    objstream.Charset = "big5"  'Charset 
    strRetXML = objstream.ReadText '取值  
    objstream.Close  
    set objstream = nothing  
    '//-----------------Obj end---------------------
    IF oHttpPost.status = 200 Then
        '//回傳的status 200 是正常執行
        response.Write("回傳的資料:" & strRetXML)
    else 
        response.write oHttpPost.status & strRetXML
    end if
    response.end() 
%>

設計一隻檔案 XMLReader.asp

XMLReader.asp
<% 
    '//================測試XML接收資料================
    Set xml = Server.CreateObject ("MSXML2.DOMDocument") 
    xml.async = False 
    xml.Load Request  '取得傳入的值 Web Request
    If xml.parseError.errorCode <> 0 Then  
        response.write "發生錯誤://" & "reason:" & xml.parseError.reason & "/Line:" & xml.parseError.line
    End If 
    
    '先將我想要找的資料節點上層定義好,若出現XML需有預設的上層文件,代表資料未讀入
    Set objNode = xml.getElementsByTagName("User")
    
    'HTML表頭資訊 若是傳回的形態要是XML,則宣告則XML
    Response.ContentType="text/html;" 
    response.write "<html>"
    response.write "    <BODY>"
    response.write "        <table>"
    for i=0 to objNode.length-1 
        response.write "            <tr><td>使用者名稱</td><td>使用者編號</td><td>使用者電話</td>"
        ID =    objNode.item(i).childnodes(0).text '第i個 <User>中的 第一個子節點的 文字
        Name =  objNode.item(i).childnodes(1).text '第i個 <User>中的 第二個子節點的 文字
        Phone = objNode.item(i).childnodes(2).text '第i個 <User>中的 第三個子節點的 文字
        response.write "            <tr><td>" & ID & "</td><td>" & Name & "</td><td>" & Phone & "</td>"
    Next
    response.write "        </table>"
    response.write "    </body>"
    response.write "</html>"
    Response.end
End Function
    
%>

製作一份標準的XML

<?xml version="1.0" encoding="utf-8"?>
<root>
    <User>
        <ID>1</ID>
        <Name><![CDATA[王曉明]]></Name>
        <Phone>02-25780908</Phone>
    </User>
    <User>
        <ID>2</ID>
        <Name><![CDATA[陳大東]]></Name>
        <Phone>02-25780908#01</Phone>
    </User>
    <User>
        <ID>3</ID>
        <Name><![CDATA[吳小寶]]></Name>
        <Phone>02-25780908#02</Phone>
    </User>
</root>

以上步驟準備完成之後,開始執行測試階段

呼叫 XMLSend.asp

頁面結果:

注意:XML格式需統一為UTF-8,有時候我們使用ASP 建立XML ,寫入文字格式會亂碼

四.如何利用Javascript傳送與接收XML
建立一個XMLSendJs.asp

XMLSendJs.asp
<%
    '//================使用FSO來處理開啟xml檔案 並讀取XML內容================
    Set fs = Server.CreateObject("Scripting.FileSystemObject")
    file_Path = Server.MapPath("User.xml")
    Const ForReading = 1, ForWriting = 2, ForAppending = 8 'Source MSDN
    Set XmlContent = fs.OpenTextFile( file_Path ,ForReading )
    
    xml = XmlContent.ReadAll    'xml檔案中的內容 other : XmlContent.Read(4) 讀取第幾行 XmlContent.ReadLine 
    XmlContent.close()
    xml = replace(xml,vbcrlf,"")
    set fs = nothing

%>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<body>
<script type="text/javascript">
xmlHttp=null;
if (window.XMLHttpRequest)
  {// code for IE7, Firefox, Opera, etc.
  xmlHttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE6, IE5
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlHttp!=null)
  {
  //xmlHttp.open("GET", "User.xml", false);
  //xmlHttp.send(null);
  //xmlDoc=xmlHttp.responseText;
  xmlDoc = '<%=xml%>';
  xmlHttp.open("POST", "XmlReader.asp", false);
  xmlHttp.send(xmlDoc);
  document.write(xmlHttp.responseText);
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
</script>
</body>
</html>

使用Jquery Ajax GetXML: XMLSendJs.asp

$.ajax({
        url:'User2.xml',
        type: 'GET',
        dataType: 'xml',//資料型態可以不設定,且此型態不可是text或html
        timeout: 1000,
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",
        success: function(xml){
            $(xml).find("User").each(function(i){  //取得xml父節點       
                var ID      =$(this).children("ID").text();     //取得子節ID
                var Name        =$(this).children("Name").text();   //取得子節點Name
                var Phone   =$(this).children("Phone").text();  //取得子節點Phone
                $('#ajaxXml').val($('#ajaxXml').val() + 'ID:' + ID + '//Name:' + Name + '//Phone' + Phone +'\n');
            })
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr.status);
            alert(thrownError);
        }
    });

五.如何利用Asp.net傳送與接收XML
建立XMLSend.aspx

XMLSend.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;

public partial class XMLsend : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebRequest requset = null;
        WebResponse response = null;
        try
        {
            string fileName = Server.MapPath("User.xml");
            string uri = "http://127.0.0.1/XMLSample/XMLRead.aspx";
            requset = WebRequest.Create(uri);
            //requset.Proxy = WebProxy.GetDefaultProxy(); // 使用proxy
            requset.Method = "POST";      
            requset.ContentType = "text/xml";
            
            //使用StreamWriter 來將Request的物件寫入到Stream中
            StreamWriter writer = new StreamWriter(requset.GetRequestStream());
            writer.WriteLine(this.GetTextFromXMLFile(fileName));
            writer.Close();
            
            response = requset.GetResponse(); //將Request送到對方頁面

        }
        catch (WebException webEx)
        {
            Response.Write("錯誤訊息A:" + webEx.Message);
        }
        catch (Exception ex)
        {
            Response.Write("錯誤訊息B:" + ex.Message);
        }
        finally
        {
            
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                //使用串流將回傳的WebResponse的內容印出
                string str = sr.ReadToEnd();
                sr.Close();
                Response.Write("回應的資料" + str);
                
            }

            //將物件關閉
            if (response != null) response.GetResponseStream().Close();
            if (requset != null) requset.GetRequestStream().Close();
          
        }   

    }
    /// Function to read xml data from local system
    /// <summary>
    /// 讀取XML資料從檔案中
    /// </summary>
    /// <param name="file">實體檔案需存在路徑或網路位置</param>
    /// <returns>傳回文字t</returns>
    private string GetTextFromXMLFile(string file)
    {
        StreamReader reader = new StreamReader(file);
        string str = reader.ReadToEnd();
        reader.Close();
        return str;
    }
}

建立XMLRead.aspx

XMLRead.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Text;

public partial class XMLRead : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Response.ContentType = "text/xml";
        // Read XML posted via HTTP
        StreamReader reader = new StreamReader(Page.Request.InputStream);
        String xmlData = reader.ReadToEnd();
        
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlData);

        //將所有User撈出來 存到 XmlNodeList
        XmlNodeList nodelist = xmlDoc.SelectNodes("//User");
        StringBuilder sb = new StringBuilder();
        //再用迴圈去跑出來
        for (int i = 0; i < nodelist.Count; i++)
        {
            //將User中的所有資料讀出
            string  ID = nodelist[i].SelectSingleNode("ID").InnerText;
            string Name = nodelist[i].SelectSingleNode("Name").InnerText;
            string Phone = nodelist[i].SelectSingleNode("Phone").InnerText;


            sb.Append("姓名:" + ID+ "||編號:" + Name + "||電話:" + Phone + "\r\n");

          

        }

        Response.Write(sb);

        //另外讀屬性的方法,File是Node,FileName是屬性

        //XmlNodeList NodeList = xmlDoc.SelectNodes("//File");

        //foreach (XmlNode item_File in NodeList)
        //{
        //    if (item_File.Attributes.GetNamedItem("FileName").Value == "")
        //    {
        //        XmlNodeList MappingList = item_File.ChildNodes;

        //        foreach (XmlNode item_Mapping in MappingList)
        //        {
        //            //DoSomeThings 
        //        }
        //    }
        //}

    }
}

六.Asp.net Web Service 的應用

撰寫WebService WSGetUserInfo.asmx

WSGetUserInfo.asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.IO;
using System.Xml;
using System.Text;

/// <summary>
/// WSGetUserInfo 的摘要描述
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。
// [System.Web.Script.Services.ScriptService]
public class WSGetUserInfo : System.Web.Services.WebService
{

    public WSGetUserInfo()
    {

        //如果使用設計的元件,請取消註解下行程式碼 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public string XMLRead(string xmlData)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlData);

        //將所有User撈出來 存到 XmlNodeList
        XmlNodeList nodelist = xmlDoc.SelectNodes("//User");
        StringBuilder sb = new StringBuilder();
        //再用迴圈去跑出來
        for (int i = 0; i < nodelist.Count; i++)
        {
            //將User中的所有資料讀出
            string ID = nodelist[i].SelectSingleNode("ID").InnerText;
            string Name = nodelist[i].SelectSingleNode("Name").InnerText;
            string Phone = nodelist[i].SelectSingleNode("Phone").InnerText;
            sb.Append("姓名:" + ID + "||編號:" + Name + "||電話:" + Phone + "\r\n");
        }

        return sb.ToString();
    }
}

呼叫Webservice (需先將Web Service 加入服務參考) XMLWSSend.aspx

XMLWSSend.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GetXML;
using System.IO;
using System.Net;

public partial class XMLWSSend : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        WSGetUserInfo ws = new WSGetUserInfo(); //調用Web Service
        string fileName = Server.MapPath("User.xml");

        string xml = GetTextFromXMLFile(fileName);
        string str = ws.XMLRead(xml);
        Response.Write(str);
        
    }
    private string GetTextFromXMLFile(string file)
    {
        StreamReader reader = new StreamReader(file);
        string str = reader.ReadToEnd();
        reader.Close();
        return str;
    }
}
← VB6 Format 找不到專案或程式庫 Android 開發環境建立 →
 
comments powered by Disqus