【问题标题】:Populate Picturebox from filenames in XML从 XML 中的文件名填充图片框
【发布时间】:2018-12-06 11:07:06
【问题描述】:

我有一个包含学生及其相关图片的 XML 文件。如何在 C# 中使用这些图像位置填充 Web 表单上的所有图片框?

 <Students>
  <Student>
    <Name> Billy Blue </Name>
    <Grade> 1 </Grade>
    <Sex> Male </Sex>
    <Age> 7 </Age>
    <Picture> c:/School/Students/BillyBlue.png </Picture>
    <Grades>
      <Score>80.5</Score>
      <Score>100.0</Score>
      <Score>70.0</Score>
    </Grades>
  </Student>

我假设它会像显示的那样在循环中完成

     public frmClassRoom()
    {
        InitializeComponent();

        var XmlDoc = XDocument.Load(ConfigurationManager.AppSettings.Get("studentFile"));
        cbTeachers.Items.Add(XmlDoc.Root.Element("Classroom").Attribute("ID").Value);
        IEnumerable<XElement> listStudents =
            from XElement in XmlDoc.Root.Elements("Classroom")
            .Where(teacher => teacher.Attribute("ID").Value == "Mrs.S")
            .Elements("Students")
            .Elements("Student")

            select XElement;


        foreach (XElement student in listStudents)
        {



        }


    }

【问题讨论】:

  • 你尝试过什么吗?如果尝试过,请分享。
  • 填充是什么意思?您想要显示的输出到底是什么?
  • 对于每个学生,我想从 节点内的字符串中选择图像并插入到图片框中。最终的网络表格将显示 28 张图片(每个学生一张)

标签: c#


【解决方案1】:

使用xml to linq获取图片列表

var xml = XDocument.Load(ConfigurationManager.AppSettings.Get("studentFile"));

var query = from c in xml.Root.Descendants("Student")
               select c.Element("Picture").Value;

List<string> pictureList = new List<string>();
foreach (string pic in query)
{
    pictureList.Add(pic);
}

然后使用asp中继器

<asp:Repeater ID="Repeater" runat="server" ItemType="System.string">
    <ItemTemplate> 
       <asp:Image ID="Image1" height="32" width="32" runat="server" ImageUrl='<%# Item %>' /> 
    </ItemTemplate>
</asp:Repeater

在代码后面

Repeater.DataSource = pictureList;
Repeater.DataBind();

任何方式你都不会看到图像,因为这是一个网络应用程序,你需要将图像放在网络服务器中。您将不得不相应地更改图片网址。

Ex: <Picture> c:/School/Students/BillyBlue.png </Picture> to
<Picture> ~/School/Students/BillyBlue.png </Picture>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多