在ASP.NET中从XML加载图像

时间:2012-06-18 21:49:16

标签: c# asp.net xml xml-parsing

我有这个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文件加载(图像应该来自网络)

2 个答案:

答案 0 :(得分:2)

有很多方法可以执行此操作,但您无法使用type控件列出/显示imageListBox。您必须使用GridView / DataList / Repeater绑定XMLDatasource,您可以在其中显示数据和图像。

假设<image>标记包含图像的相对网址。

<?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();

答案 1 :(得分:0)

textfield