最近刚学C#,很多地方不会,边学边写了一个类,用于读取xml文件里的数据。

xml文件定义如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
     <path >c:\windows</path>
</configuration>

下面是读取xml文件的类:

 xml
{
    class readXML
    {
        
private string filename; //文件路径
        public string str=null;

        
//构造函数,filename是xml文件的路径
        public readXML(string filename) {
            
this.filename = filename;
        }

        
public string getPath(string id, string str) {
            XmlTextReader reader 
= new XmlTextReader(filename);
           
            
while (reader.Read())
            {
                
if (reader.Name == str && reader.GetAttribute("id"== id)
                {
                    str 
= reader.ReadString();
                    reader.Close();
                    
return str;
                }
            }
            reader.Close();
            
return null;
        }
    }

 

此类的getPath()方法用于通过id值和path子元素,获得相应的元素值。

相关文章: