0

我有这个 XML 文件,比如说(Sample.xml)

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

<drinks>
  <drink>
    <type>Coke </type>
    <image>some.jpg or (url) </image>
    <price> $5 </price>
  </drink>
  <drink>
    <type>Pepsi</type>
    <image>some.jpg or (url) </image>
    <price> $2 </price>
  </drink>
  </drinks>

我也有一个列表框,它绑定到 XML 文件。

<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" 
        DataSourceID="XmlDataSource2" DataTextField="drinks/drink/type" Height="198px" Width="181px">
    </asp:ListBox>
    <asp:XmlDataSource ID="XmlDataSource2" runat="server" DataFile="~/XMLFile.xml">
    </asp:XmlDataSource>

我怎样才能做到这一点?好吧,为了清楚地解释我的问题,我想这样做,产品和图像的链接应该从 xml 文件加载(图像应该是来自网络的 url)

4

2 回答 2

2

有很多方法可以做到这一点,但你不能列出/显示和type控制。您应该必须使用 GridView/DataList/Repeater 来绑定 XMLDatasource,您可以在其中显示数据和图像。imageListBox

假设<image>标签包含图像的相对 url。

<?xml version="1.0" encoding="utf-8" ?>
<drinks>
  <drink>
    <type>Coke </type>
    <image>~/Images/image1.png</image>
    <price> $5 </price>
  </drink>
  ....
</drinks>

并且 ASP.NET 标记将是:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataSourceID="XmlDataSource1">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="Label1" 
                           runat="server" 
                           Text='<%# XPath("type") %>'></asp:Label>
                <asp:Image ID="Image1"
                           runat="server" Height="43px" 
                           ImageUrl='<%# XPath("image") %>' 
                           Width="35px" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile.xml" 
    XPath="drinks/drink"></asp:XmlDataSource>

您还可以选择Linq-XML解析 XML 文档并准备匿名或键入的List<T>.

XDocument doc = XDocument.Load(MapPath("~/XMLFile.xml"));
 var result = from ele in doc.Descendants("drink")
               select new
                 {
                   Type=ele.Element("type").Value,
                   Image=ele.Element("image").Value
                 };

 GridView1.DataSource = result.ToList();
 GridView1.DataBind();
于 2012-06-19T02:21:26.737 回答
0
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
DataSourceID="XmlDataSource1">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
           <asp:Label ID="Label1" runat="server" Text='<%Eval("name")%>'>
                   </asp:Label>                                          
       <asp:Image ID="Image1" runat="server" Height="43px" ImageUrl='<%# Eval("image" )%>' Width="35px" />       
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

于 2015-12-31T07:34:26.693 回答