C# 操作 XML 源码

本文分享了一个实用的XML解析类,包括读取、修改、添加和删除XML文件的功能。通过这个类可以轻松实现XML文件的管理和数据提取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这段时间频繁的在Excel、XML、数据库之间倒腾数据,于是积累之下,写了不少的操作XML的方法。今天整理了一下,聚合成一个类,发上来给那些需要帮助的朋友吧。

大家可以先看看试试,有些地方可能写的不是很完善,如果你在使用中发现有什么问题或是有更好的建议,麻烦告诉一声,用我们共同的办量一起来完善吧。

using System;
using System.Collections;
using System.Xml;
using System.IO;
using System.Windows.Forms;

namespace Test
{
    
public class XmlParser
    
{
        
private XmlDocument doc = null;
        
private XmlElement root = null;

        
/// <summary>
        
/// 读取 Xml 文件
        
/// </summary>
        
/// <param name="fName">文件名</param>
        
/// <param name="isFile"></param>

        public XmlParser(string fName, bool isFile)
        
{
            
try
            
{
                
if (isFile)
                
{
                    
if (!File.Exists(fName))
                    
{
                        
throw new Exception("找不到xml文件,请与管理员联系!");
                    }

                    doc 
= new XmlDocument();
                    doc.Load(fName);
                    root 
= doc.DocumentElement;
                }

                
else
                
{
                    doc 
= new XmlDocument();
                    doc.LoadXml(fName);
                    root 
= doc.DocumentElement;
                }

            }

            
catch (Exception e)
            
{
                MessageBox.Show(e.Message);
            }

        }


        
/// <summary>
        
/// 返回根节点
        
/// </summary>

        public XmlElement getRoot()
        
{
            
return this.root;
        }


        
/// <summary>
        
/// 返回当前节点的子节点
        
/// </summary>
        
/// <returns></returns>

        public string getXmlStr()
        
{
            
return doc.InnerXml;
        }


        
/// <summary>
        
/// 返回节点集合
        
/// </summary>

        public ArrayList getAllCldNode(XmlElement e, string name)
        
{
            ArrayList al 
= new ArrayList();
            
if (e != null)
            
{
                XmlNodeList nl 
= e.ChildNodes;
                
for (int i = 0; i < nl.Count; i++)
                
{
                    XmlElement tmp 
= (XmlElement)nl[i];
                    
if (tmp != null)
                    
{
                        
if (tmp.Name.Equals(name))
                        
{
                            al.Add(tmp);
                        }

                    }

                }

            }

            
return al;
        }


        
/// <summary>
        
/// 返回指定的节点
        
/// </summary>
        
/// <param name="e">父节点</param>
        
/// <param name="name">节点名称</param>
        
/// <returns>节点名称</returns>

        public XmlElement getSingleCldNode(XmlElement e, string name)
        
{
            XmlElement result 
= null;
            
if (e != null)
            
{
                XmlNodeList nl 
= e.ChildNodes;
                
for (int i = 0; i < nl.Count; i++)
                
{
                    XmlElement tmp 
= (XmlElement)nl[i];
                    
if (tmp != null)
                    
{
                        
if (tmp.Name.Equals(name))
                        
{
                            result 
= tmp;
                            
break;
                        }

                    }

                }

            }

            
return result;
        }


        
/// <summary>
        
/// 遍历节点树,查找指定的节点
        
/// </summary>
        
/// <param name="e"></param>
        
/// <param name="nodeName"></param>
        
/// <returns></returns>

        public XmlElement getSpecifyNode(XmlElement e, string nodeName)
        
{
            XmlElement result 
= null;
            XmlNodeList nl 
= e.GetElementsByTagName(nodeName);
            
for (int i = 0; i < nl.Count; i++)
            
{
                result 
= (XmlElement)nl[i];
            }

            
return result;
        }


        
/// <summary>
        
/// 更改节点文本值
        
/// </summary>

        public void setElementText(XmlElement e, string text)
        
{
            e.InnerText 
= text;
        }


        
/// <summary>
        
/// 添加新节点
        
/// </summary>

        public XmlElement addElement(XmlElement e,string nodeName)
        
{
            XmlElement xe 
= doc.CreateElement(nodeName);
            e.AppendChild(xe);
            
return xe;
        }


        
/// <summary>
        
/// 删除当前节点下所有子节点
        
/// </summary>
        
/// <param name="e"></param>

        public void delElement(XmlElement e)
        
{
            e.RemoveAll();
        }


        
public DateTime getElementDateTime(XmlElement e, string name, DateTime DefValue)
        
{
            DateTime result 
= DefValue;
            XmlElement tmp 
= getSingleCldNode(e, name);
            
if (tmp != null)
            
{
                
string tmpstr = tmp.InnerText;
                
if (tmpstr == null) result = DefValue;
                
else
                
{
                    
try
                    
{
                        result 
= Convert.ToDateTime(tmpstr);
                    }

                    
catch (Exception ex)
                    
{
                        MessageBox.Show(ex.Message);
                    }

                }

            }

            
return result;
        }


        
/// <summary>
        
/// 获得指定节点的文本
        
/// </summary>
        
/// <param name="e">XmlElement</param>
        
/// <param name="name">节点名称</param>
        
/// <param name="DefValue"></param>
        
/// <returns></returns>

        public string getElementTxt(XmlElement e, string name, string DefValue)
        
{
            
string result = DefValue;
            XmlElement tmp 
= getSingleCldNode(e, name);
            
if (tmp != null)
            
{
                
string tmpstr = tmp.InnerText;
                
if (tmpstr == null) result = DefValue; else result = tmpstr;
            }

            
return result;
        }


        
public Boolean getElementBool(XmlElement e, string name, Boolean DefValue)
        
{
            Boolean result 
= DefValue;
            XmlElement tmp 
= getSingleCldNode(e, name);
            
if (tmp != null)
            
{
                
string tmpstr = tmp.InnerText;
                
if (tmpstr == null) result = DefValue;
                
else
                
{
                    
if (tmpstr.Equals("true"))
                    
{
                        result 
= true;
                    }

                    
else
                    
{
                        result 
= false;
                    }

                }

            }

            
return result;
        }


        
public DateTime getDateTime(XmlElement e, DateTime DefValue)
        
{
            DateTime result 
= DefValue;

            
if (e != null)
            
{
                
string tmpstr = e.InnerText;
                
try
                
{
                    result 
= Convert.ToDateTime(tmpstr);
                }

                
catch (Exception ex)
                
{
                    result 
= DefValue;
                }


            }

            
return result;
        }


        
public string getTxt(XmlElement e, string DefValue)
        
{
            
string result = DefValue;
            
if (e != null)
            
{
                
string tmpstr = e.InnerText;
                
if (tmpstr == null) result = DefValue; else result = tmpstr;
            }

            
return result;
        }


        
public int getElementInt(XmlElement e, string name, int DefValue)
        
{
            
int result = DefValue;
            XmlElement tmp 
= getSingleCldNode(e, name);
            
if (tmp != null)
            
{
                
string tmpstr = tmp.InnerText;
                
if ((tmpstr != null&& (!tmpstr.Equals("")))
                
{
                    result 
= Convert.ToInt32(tmpstr);
                }

            }

            
return result;
        }


        
public long getElementlong(XmlElement e, string name, long DefValue)
        
{
            
long result = DefValue;
            XmlElement tmp 
= getSingleCldNode(e, name);
            
if (tmp != null)
            
{
                
string tmpstr = tmp.InnerText;
                
if ((tmpstr != null&& (!tmpstr.Equals("")))
                
{
                    result 
= Convert.ToInt64(tmpstr);
                }

            }

            
return result;
        }


        
public int getAttributeInt(XmlElement e, string name, int DefValue)
        
{
            
int result = DefValue;
            
if (e != null)
            
{
                
if (e.HasAttribute(name))
                
{
                    
string temp = e.GetAttribute(name);
                    
if (temp == null) result = DefValue;
                    
else
                        result 
= Convert.ToInt32(temp);
                }

            }

            
return result;
        }


        
public long getAttributeLong(XmlElement e, string name, long DefValue)
        
{
            
long result = DefValue;
            
if (e != null)
            
{
                
if (e.HasAttribute(name))
                
{
                    
string temp = e.GetAttribute(name);
                    
if (temp == null) result = DefValue;
                    
else
                        result 
= Convert.ToInt64(temp);
                }

            }

            
return result;
        }


        
public int getInt(XmlElement e, int DefValue)
        
{
            
int result = DefValue;
            
if (e != null)
            
{
                
string tmpstr = e.InnerText;
                
if ((tmpstr != null&& (!tmpstr.Equals("")))
                
{
                    result 
= Convert.ToInt32(tmpstr);
                }

            }

            
return result;
        }


        
public long getLong(XmlElement e, long DefValue)
        
{
            
long result = DefValue;
            
if (e != null)
            
{
                
string tmpstr = e.InnerText;
                
if ((tmpstr != null&& (!tmpstr.Equals("")))
                
{
                    result 
= Convert.ToInt64(tmpstr);
                }

            }

            
return result;
        }


        
/// <summary>
        
/// 取得节点属性值
        
/// </summary>
        
/// <param name="e"></param>
        
/// <param name="name"></param>
        
/// <param name="DefValue"></param>
        
/// <returns></returns>

        public string getAttrTxt(XmlElement e, string name, string DefValue)
        
{
            
string result = DefValue;
            
if (e != null)
            
{
                
if (e.HasAttributes)
                
{
                    XmlAttribute xa 
= e.GetAttributeNode(name);
                    
if (xa != null)
                    
{
                        
string tmp = xa.InnerText;
                        
if (tmp != null) result = tmp;
                    }

                }

            }

            
return result;
        }


        
public void setAttrTxt(XmlElement e, string attName, string attValue)
        
{
            e.SetAttribute(attName, attValue);
        }


        
/// <summary>
        
/// 保存 Xml 文件
        
/// </summary>

        public void saveXml(string FName)
        
{
            doc.Save(FName);
        }

    }

}
C# XML文件读写操作源码,以及如何调用,注释详解,有任何问题请留言, 以下截取xml文件和部分调用代码段: * ++++++++++++++++++++++++++++++++++++++ <?xml version="1.0" encoding="utf-8" standalone="no"?> <!--TestPlugins的信息--> <!--DataPlugins的信息--> * ++++++++++++++++++++++++++++ xml xl = new xml(); xl.XMLWriteRootNode("info"); //XmlElement Eml1 = xl.XMLReadNode("",0); //XmlElement Eml2 = xl.XMLReadNode("DataPlugins", 1); //XmlElement Eml4 = xl.XMLReadNode("DeviceInfo", 2); // TestPlugins XmlElement testPlugins = xl.XMLCreateNode("TestPlugins", null, null); xl.XMLInsertNode("info", 0, "TestPlugins的信息", testPlugins); // FixturePlugin XmlElement fixturePlugin = xl.XMLCreateNode("TestPlugin", null, new Dictionary() { { "Type", "FixturePlugin" } }); xl.XMLInsertNode(testPlugins.LocalName, 1, null, fixturePlugin); // DUTPlugin XmlElement DUTPlugin = (XmlElement)fixturePlugin.CloneNode(true);// xl.XMLCreateNode("TestPlugin", null, new Dictionary() { { "Type", "DUTPlugin" } }); DUTPlugin.SetAttribute("Type", "DUTPlugin"); xl.XMLInsertNode(testPlugins.LocalName, 1, null, DUTPlugin); // Agilent34461APlugin XmlElement Agilent34461APlugin = xl.XMLCreateNode("TestPlugin", null, new Dictionary() { { "Type", "Agilent34461APlugin" } }); xl.XMLInsertNode(testPlugins.LocalName, 1, null, Agilent34461APlugin); // ================================== // DataPlugins XmlElement dataPlugins = xl.XMLCreateNode("DataPlugins", null, null); xl.XMLInsertNode("info", 0, "DataPlugins的信息", dataPlugins); // CSVLogPlugin XmlElement csvlogPlugin = xl.XMLCreateNode("DataPlugin", null, new Dictionary() { { "Type", "CSVLogPlugin" } }); xl.XMLInsertNode(dataPlugins.LocalName, 1, null, csvlogPlugin); XmlElement uartlogPlugin = (XmlElement)csvlogPlugin.CloneNode(true); uartlogPlugin.SetAttribute("Type", "UartLogPlugin"); xl.XMLInsertNode(dataPlugins.LocalName, 1, null, uartlogPlugin); XmlElement testlogPlugin = (XmlElement)csvlogPlugin.CloneNode(true); testlogPlugin.SetAttribute("Type", "TestLogPlugin"); xl.XMLInsertNode(dataPlugins.LocalName, 1, null, testlogPlugin); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值