在C#.net中读取XML文件(动态属性) [英] Read XML file in C#.net (Dynamic Property)

查看:148
本文介绍了在C#.net中读取XML文件(动态属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友们,
步骤:1
我在表单中(动态地)创建了一个文本框,组合框和复选框.
步骤:2
像这样的结构将值插入XML.

Hi friends,
Step:1
I have a created Textbox,combo box and check box in my form(Dynamically).
Step:2
Insert values into XML like this structure.

<?xml version="1.0"?>
<Root>
  <port0>COM5-Naraayanan-True</port0>
  <port1>COM6-Mohan-False</port1>
</Root>


在这里,COM5是组合框值
Naraayanan是一个文本框值
True是一个Checkbox值(已选中).
但是我的问题是当我读取XML时.除Checkbox以外,我得到了一个结果.请告诉我如何解决我的问题.
我给我的readxml编码
gb是我的表单中的群组框".


Here ,COM5 is a Combobox value
Naraayanan is a textbox value
True is a Checkbox value(Checked).
But my Problem is when I read a XML. I got a result except Checkbox.Please tell me how to solve my Problem.
I give my readxml coding
gb is a Group Box in my form .

string sFilename = xmlpath;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(sFilename);
            XmlElement rootElem = xmlDoc.DocumentElement; //Gets the root element, in your xml its "Root"
            for (int i = 0; i < rootElem.ChildNodes.Count ; i++)
            {
                string name = rootElem.ChildNodes[i].Name;
                string value = rootElem.ChildNodes[i].InnerText;
                string[] words = value.Split('-');
                    txt1 = words[0];
                    txt2 = words[1];
                    txt3 = words[2];
                   gb.Controls["Combobox" + (i + 0).ToString()].Text = txt1;
                   gb.Controls["Textbox" + (i + 0).ToString()].Text = txt2;
                   gb.Controls["RB" + (i + 0).ToString()].Text    = txt3;

            }


最后一行是问题.请如何解决我的问题?
问候,
Lakshmi Narayanan


Last line is problem.Please How to solve my Problem?
Regards,
Lakshmi Narayanan

推荐答案

我认为您应该替换行
I think you should replace the line
gb.Controls["RB" + (i + 0).ToString()].Text    = txt3;




with

CheckBox cb = gb.Controls["RB" + i.ToString()] as CheckBox;
cb.Checked = (txt3=="True");




顺便说一句,您不需要txt1txt2txt3变量.
顺便说一句,您的XML定义不明确:每个连字符分隔的值都应有其自己的节点.




BTW you don''t need txt1,txt2,txt3 variables.
BTW2 your XML is poorly defined: each of the hyphen-separated values should have its own node.


我认为您的问题在于方法.您正在尝试直接保留UI.相反,您确实需要建立一个中间数据层并仅保留该数据层.

它看起来像是额外的工作,但是如果不这样做,将会导致您今后陷入僵局.通过执行当前正在执行的操作,您将无法升级或替换UI部件.请记住,您需要将UI与功能的通用部分和特定于应用程序的部分隔离开来,但是您要做的却恰恰相反.

现在,您根本不需要创建XML层,正如我在最近的答案中使用Data Contract的解决方案中所述:
通过C#.net在XML中动态创建元素 [ ^ ].

您需要开发将数据绑定到UI(填充)和(UI到数据)的方法,以将所有内容粘合在一起.
利用松散耦合的好处( http://en.wikipedia.org/wiki/Loose_coupling [^ ])!

-SA
I think your problem is the approach. You''re trying to persist UI directly. Instead, you really need to make an intermediate data layer and persist only the data layer.

It looks as extra work but failure to do so will lead you to the dead end in future. By doing what you''re doing right now you block your way to upgrade or replace your UI part. Remember, you need to isolate you UI from both the universal and application-specific part of functionality, but you''re doing just the opposite.

Now, you don''t need to create XML layer at all, as I explained in my solution using Data Contract in my recent answer:
Dynamic creation of elements in XML via C#.net[^].

You need to develop data-to-UI (population) and (UI-to-data) methods which will glue things together.
Use the benefits of loose coupling (http://en.wikipedia.org/wiki/Loose_coupling[^])!

—SA


public class Properties
{
    private Dictionary<String, String> list;
    private String filename;

    public Properties(String file)
    {
        reload(file);
    }

    public String get(String field, String defValue)
    {
        return (get(field) == null) ? (defValue) : (get(field));
    }
    public String get(String field)
    {
        return (list.ContainsKey(field))?(list[field]):(null);
    }

    public void set(String field, Object value)
    {
        if (!list.ContainsKey(field))
            list.Add(field, value.ToString());
        else
            list[field] = value.ToString();
    }

    public void Save()
    {
        Save(this.filename);
    }

    public void Save(String filename)
    {
        this.filename = filename;

        if (!System.IO.File.Exists(filename))
            System.IO.File.Create(filename);

        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);

        foreach(String prop in list.Keys.ToArray())
            if (!String.IsNullOrWhiteSpace(list[prop]))
                file.WriteLine(prop + "=" + list[prop]);

        file.Close();
    }

    public void reload()
    {
        reload(this.filename);
    }

    public void reload(String filename)
    {
        this.filename = filename;
        list = new Dictionary<String, String>();

        if (System.IO.File.Exists(filename))
            loadFromFile(filename);
        else
            System.IO.File.Create(filename);
    }

    private void loadFromFile(String file)
    {
        foreach (String line in System.IO.File.ReadAllLines(file))
        {
            if ((!String.IsNullOrEmpty(line)) &&
                (!line.StartsWith(";")) &&
                (!line.StartsWith("#")) &&
                (!line.StartsWith("'")) &&
                (line.Contains('=')))
            {
                int index = line.IndexOf('=');
                String key = line.Substring(0, index).Trim();
                String value = line.Substring(index + 1).Trim();

                if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                    (value.StartsWith("'") && value.EndsWith("'")))
                {
                    value = value.Substring(1, value.Length - 2);
                }

                try
                {
                    //ignore dublicates
                    list.Add(key, value);
                }
                catch { }
            }
        }
    }


}


这篇关于在C#.net中读取XML文件(动态属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆