运行时ASP.Net GridView和XMLDataSource绑定

时间:2012-01-03 23:41:30

标签: c# asp.net

我正在使用ASP.Net 2.0并尝试在运行时使用GridView和XMLDataSource显示转换后的xml数据。

这是我的xml数据(Input.xml):

<catalog>
<cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
</cd>
<cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
</cd>
<cd>
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
</cd>
<cd>
    <title>Still got the blues</title>
    <artist>Gary Moore</artist>
    <country>UK</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
</cd>
</catalog>

这是变换(Transform.xslt):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
    <CDCatalog>
        <xsl:apply-templates/>
    </CDCatalog>
</xsl:template>

<xsl:template match="cd">
  <CD>
  <xsl:apply-templates select="*">
        </xsl:apply-templates>
  </CD>
</xsl:template>


<xsl:template match="catalog/cd/*">
            <xsl:attribute name="{local-name()}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

为了您的参考,这将是转换后的xml:

<CDCatalog>
<CD title="Empire Burlesque" artist="Bob Dylan" country="USA" company="Columbia" price="10.90" year="1985"/>
<CD title="Hide your heart" artist="Bonnie Tyler" country="UK" company="CBS Records" price="9.90" year="1988"/>
<CD title="Greatest Hits" artist="Dolly Parton" country="USA" company="RCA" price="9.90" year="1982"/>
<CD title="Still got the blues" artist="Gary Moore" country="UK" company="Virgin records" price="10.20" year="1990"/>
</CDCatalog>

现在这就是我在C#代码中所做的事情(GridView1是在.aspx页面上创建的):

        XmlDataSource xmlDS = new XmlDataSource();
        xmlDS.EnableCaching = false;
        xmlDS.DataFile = "~/Input.xml";
        xmlDS.TransformFile = "~/Transform.xslt";
        xmlDS.XPath = "/CDCatalog/CD";
        GridView1.DataSourceID = xmlDS.ID;
        GridView1.DataBind();
        GridView1.Visible = true;

我在GridView中看不到任何数据。我在互联网上查了很多但是他们一般都在设计时谈到在aspx页面中做这种事情,而不是在代码中运行时。我不确定这是否是对GridView / XMLDataSource绑定的限制,或者我是否做错了。我很感激任何帮助。 谢谢,Srinivas

1 个答案:

答案 0 :(得分:2)

只需更改此行:

GridView1.DataSourceID = xmlDS.ID;

到此:

GridView1.DataSource = xmlDS;

enter image description here