零代碼讀取XML資料

來源:互聯網
上載者:User

        首先聲明:讀取XML資料並不需要零代碼實現,如果用DataSet同樣可以讀取。比如:

        

            //DataSet dsFailSystem = new DataSet();
            //string FailSystemfilepath = Server.MapPath("../XMLFile/FailSystem.xml");
            //dsFailSystem.ReadXml(FailSystemfilepath);          

            //this.dpFailSystem.DataSource = dsFailSystem;
            //this.dpFailSystem.DataMember = "FailSystem";
            //this.dpFailSystem.DataTextField = "FailSystemName";
            //this.dpFailSystem.DataValueField = "FailSystemName";           
            //this.dpFailSystem.DataBind();

 

           這樣一段代碼足夠把XML的資料讀取出來,並且在DropDownList顯示出來。但是這種寫代碼還是有點問題:比如使用者不願意輸入這麼多代碼、並且容易出錯。所以在此對代碼實現不多介紹,只介紹零代碼如何?讀取XML資料。

 

           步驟如下:

           1、書寫XML檔案,如下:

<?xml version="1.0" encoding="utf-8" ?>
<FailCurrectWayDataSet>
  <FailCurrectWay>
    <FailCurrectWayName>更換</FailCurrectWayName>
  </FailCurrectWay>
  <FailCurrectWay>
    <FailCurrectWayName>修理</FailCurrectWayName>
  </FailCurrectWay>
  <FailCurrectWay>
    <FailCurrectWayName>改進設計</FailCurrectWayName>
  </FailCurrectWay>
  <FailCurrectWay>
    <FailCurrectWayName>其他方式</FailCurrectWayName>
  </FailCurrectWay>
</FailCurrectWayDataSet>

2、如果是GridView控制項,可以直接在選擇資料庫的時候選擇XML檔案,然後選擇剛剛建立的XML檔案。在寫個XPath:/FailCurrectWayDataSet/FailCurrectWay即可。

3、如果是DropDownList控制項,寫XPath是沒有用的,頁面會提示錯誤。找不到XPath,此時需要另外一個檔案:XSL檔案做轉化檔案,如下:

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="FailCurrectWayDataSet">
    <FailCurrectWayDataSet>
      <xsl:apply-templates select="FailCurrectWay"/>
    </FailCurrectWayDataSet>
  </xsl:template>
  <xsl:template match="FailCurrectWay">
    <FailCurrectWay>
      <xsl:attribute name="FailCurrectWayName">
        <xsl:apply-templates select="FailCurrectWayName"/>
      </xsl:attribute>
    </FailCurrectWay>
  </xsl:template>
</xsl:stylesheet>

4、有了這個檔案,使用者在選擇XML檔案後,然後選擇轉化檔案即可,此時無須寫XPath。

5、最後選擇DataTextField以及DataValueField即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.