在C#中读取一个简单的XML配置文件

时间:2017-02-27 21:36:49

标签: c# .net xml visual-studio

我很难记住如何做到这一点,我看到的大多数例子都没有真正涵盖我的问题。我试图阅读下面的XML文件,这样如果用户从下拉菜单中选择工具类型,则所述工具的变量将在屏幕上填充表单。我不知道如何收集特定工具的所有元素/属性。

<?xml version="1.0" encoding="UTF-8"?> 
<Tool_menu>
    <tool name="A">
        <emails>
            <email severity="Low">
                <address>reg@test.com</address>
            </email>
            <email severity="High">
                <address>notReg@test.com</address>
            </email>
        </emails>
        <configuration_list>
            <configuration>
                <name>Confg1</name>
            </configuration>
            <configuration>
                <name>Confg2</name>
            </configuration>
            <configuration>
                <name>Confg3</name>
            </configuration>
            <configuration>
                <name>Confg4</name>
            </configuration>
        </configuration_list>
    </tool>
    <tool name="B">
        <emails>
            <email severity="Low">
                <address>reg@test.com</address>
            </email>
            <email severity="High">
                <address>notReg@test.com</address>
            </email>
        </emails>
        <configuration_list>
            <configuration>
                <name>n/a</name>
            </configuration>
            <configuration>
                <name>n/a</name>
            </configuration>
        </configuration_list>
    </tool>
    <tool name="C">
        <emails>
            <email severity="Low">
                <address>reg@test.com</address>
            </email>
            <email severity="High">
                <address>notReg@test.com</address>
            </email>
        </emails>
        <configuration_list>
            <configuration>
                <name>200Scope</name>
            </configuration>
            <configuration>
                <name>300Scope</name>
            </configuration>
            <configuration>
                <name>600Scope</name>
            </configuration>
            <configuration>
                <name>900Scope</name>
            </configuration>
        </configuration_list>
    </tool>
</Tool_menu> 

我想要的是让用户选择工具C&#39;并查看工具C上可用的配置列表,工具名称以及电子邮件发送者(低/高严重性)选项的下拉列表

**使用.net 4.5

2 个答案:

答案 0 :(得分:4)

使用XPath访问节点。 请查看一些tutorials herehere

在您的情况下,访问工具C可以这样实现:

XmlDocument doc = new XmlDocument();
doc.Load(@"c:\temp\tools.xml");

var toolCemails = doc.SelectNodes("//tool[@name='C']/emails/email"); //two nodes with email tag
var toolCconfigs = doc.SelectNodes("//tool[@name='C']/configuration_list/configuration"); //four config nodes

答案 1 :(得分:1)

您可以在SO:LINQ to read XML

上查看此帖子

编辑:另外,在您的问题下面的评论中,@ zx485发布了指向另一个有用的SO帖子的链接,在这里:Bind XML data to a Dropdownlist c#

这可能有助于您入门。如果没有,请尝试将您的问题缩小到更具体的范围 - 最好使用一些我们可以帮助您的代码。

由于您的问题现在正在撰写,似乎您要求我们为您执行此操作而不是帮助您解决特定问题