c#编写一个程序,通过给出的ID去自动读取xml配置文件中ID对应的相应名称
时间: 2024-05-01 17:23:46 浏览: 20
假设xml文件的格式如下:
```xml
<config>
<item id="1" name="Apple" />
<item id="2" name="Banana" />
<item id="3" name="Orange" />
</config>
```
则可以使用以下代码来实现:
```csharp
using System;
using System.Xml;
namespace ReadXmlByName
{
class Program
{
static void Main(string[] args)
{
int id = 1; // 要查找的ID
string configPath = "config.xml"; // xml文件路径
string name = GetNameById(id, configPath);
Console.WriteLine($"ID:{id} 对应的名称为:{name}");
}
static string GetNameById(int id, string configPath)
{
XmlDocument doc = new XmlDocument();
doc.Load(configPath);
XmlNode node = doc.SelectSingleNode($"/config/item[@id='{id}']");
if (node != null)
{
return node.Attributes["name"].Value;
}
else
{
throw new Exception($"ID:{id} 不存在于配置文件中!");
}
}
}
}
```
运行结果:
```
ID:1 对应的名称为:Apple
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)