繁体   English   中英

如何在C#表单应用程序中使用xml基于xml文件中的用户输入获取标签的文本

[英]How to use xml with c# form application To get text for Lables Based on user Input from xml file

我正在使用C#开发Win表单应用程序,我想向我的应用程序添加功能,通过该功能我可以根据用户输入更改lable.text。

我想使用xml文件,因此我可以将一些标签设置为预定义值,这些值可以随时更改,而无需重新编译应用程序或更改应用程序的语言

我有一个要在表单应用程序中使用的xml文件

    <?xml version="1.0" encoding="utf-8" ?>
  <product>
    <product_id>1</product_id>
    <product_name>Product 1</product_name>
    <product_price>1000</product_price>
  </product>
  <product>
    <product_id>2</product_id>
    <product_name>Product 2</product_name>
    <product_price>2000</product_price>
  </product>
  <product>
    <product_id>3</product_id>
    <product_name>Product 3</product_name>
    <product_price>3000</product_price>
  </product>
  <product>
    <product_id>4</product_id>
    <product_name>Product 4</product_name>
    <product_price>4000</product_price>
  </product>

在我的应用程序中,我有一些文本用于textbox1,textbox2textbox3以及Lables作为Lable1,Lable2,Lable3

关于textbox1中的 文本更改 ,我想更改lable1.text的值。 例如,根据id,如果用户在textbox1中输入1,则标签文本应更改为产品1

作为C#和编程的初学者,不知道如何使它工作。

您可以使用Linq将xml解析为Xml 在文本更改事件上,请执行以下操作:

int id;
if (!Int32.TryParse(textbox1.Text, out id))
    return; // do nothing if not integer entered

XDocument xdoc = XDocument.Load(path_to_xml_file);
var product = xdoc.Descendants("product")
                  .FirstOrDefault(p => (int)p.Element("product_id") == id);

lable1.Text = (product == null) ? "" : (string)product.Element("product_name");

顺便说一句,当问问题时,请始终提供您已经拥有的代码,以告诉我们您遇到的问题。 另外,正如我在问题下评论的那样,您的xml无效,因为它有几个根元素。 将所有产品元素包装到某个根目录中,例如<products>

考虑用C#读写XML来解决问题,并寻找每个答案,对于设置,也可以使用Settings.Settings文件,如果希望更改或不更改,则选择User或Application。

建立XML

读取XML XPath

Ream XML XmlReader,单遍

设定文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM