关于C#处理xml文件的小方法

首先引入命名空间System.Xml;

声明对象:        
        public XmlDocument xmlDoc = null;
        public XmlNode xmlNode=null;
        public XmlElement xmlEle = null;

 

 

创建xml文件:
public void CreateXml(string xmlPath) {
            try {
                xmlDoc = new XmlDocument();
                xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "version=1.0", "");
                xmlDoc.AppendChild(xmlNode);
                xmlEle = xmlDoc.CreateElement("Books");
                xmlEle.SetAttribute("id","05020");
                xmlEle.InnerText = "05020";
                xmlDoc.AppendChild(xmlEle);
                for(int i=0;i<9;i++)
                {
                    XmlElement xmlEle2 = xmlDoc.CreateElement("SubBooks"+i);
                    xmlEle2.SetAttribute("id","05020"+i);
                    xmlEle2.InnerText = "abc";
                    xmlEle.AppendChild(xmlEle2);
                }
            }
            catch (Exception e2) { throw new Exception(e2.Message); }
            xmlDoc.Save(xmlPath);
        }

 

 


public void AlterXml(string xmlPath) {
            try {
                xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                try {
                    XmlNode xmlNode = xmlDoc.SelectSingleNode("Books");
                    XmlElement ele = (XmlElement)xmlNode;
                    ele.SetAttribute("id","0123456");
                    xmlDoc.Save(xmlPath);
                }
                catch (Exception e2) { throw new Exception(e2.Message); }
            
            }
            catch (Exception e2) { }
        }
 

 

 

 

读取数据:
public void ReadXml(string xmlPath) {
            xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            try {
                XmlNode xmlNode = (XmlNode)xmlDoc.SelectSingleNode("Books");
                XmlNodeList xnl = xmlNode.ChildNodes;
                string msg = "";
                foreach (XmlNode xn in xnl) {
                    //XmlElement xe = (XmlElement)xn;
                    msg+= xn.InnerText.ToString() + "/n/r";
                }
                MessageBox.Show(msg);
            }
            catch (Exception e2) { throw new Exception(e2.Message); }
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值