zoukankan      html  css  js  c++  java
  • C# XML操作

    public static void Main()   
            {
                string ids="1,2,3,4,5,6,9";
                string filePath = "c://c/d/qq.xml";
                string xmlPath = "getsomething/news/list/store";
                string subString = xmlPath.Substring(0,xmlPath.LastIndexOf('/'));
                string now = xmlPath.Substring(xmlPath.LastIndexOf('/')+1);
                
                if (!IsExists(filePath))
                {
                    Exists(filePath);
                }
                doc.Load(filePath);
                xml = (XmlElement)doc.FirstChild;
                string parentPath = xmlPath.Substring(0, xmlPath.LastIndexOf('/'));
                string nowNode = xmlPath.Substring(xmlPath.LastIndexOf('/') + 1);
                XmlNode node = doc.SelectSingleNode(parentPath);
                XmlNode oldNode = doc.SelectSingleNode(xmlPath);
                if (node == null)
                {
                    node = CreateXmlNode(parentPath);
                    XmlElement el = doc.CreateElement(nowNode);
                    XmlAttribute attr = doc.CreateAttribute("ids");
                    attr.Value = ids;
                    el.Attributes.Append(attr);
                    node.AppendChild(el);
                }
                else
                {
                    XmlElement el = doc.CreateElement(nowNode);
                    XmlAttribute attr = doc.CreateAttribute("ids");
                    attr.Value = ids;
                    el.Attributes.Append(attr);
                    if (oldNode == null)
                    {
                        node.AppendChild(el);
                    }
                    else
                    {
                        node.ReplaceChild(el, oldNode);
                    }
                }
                doc.Save(filePath);
                Console.ReadKey();
            }
    
    
     public static XmlNode CreateXmlNode(string xmlPath)
            {
                string[] xmls = xmlPath.Split('/');
                string root = "";
                XmlNode parent =xml;
                for (int i = 0; i < xmls.Length;i++)
                {
                    XmlNode node = doc.DocumentElement.SelectSingleNode(root+"/"+xmls[i]);
                    if (node == null)
                    {
                        XmlElement xmle = doc.CreateElement(xmls[i]);
                        parent.AppendChild(xmle);
                    }
                    root = root + "/" + xmls[i];
                    parent =doc.DocumentElement.SelectSingleNode(root);
                }
                return parent;
            }
  • 相关阅读:
    JUnit常用断言及注解
    centos7 yum快速安装LNMP
    ceph问题汇总
    selinux介绍/状态查看/开启/关闭
    linux 修改主机名
    CentOS 7部署 Ceph分布式存储架构
    如何判断当前系统运行在物理机上还是虚拟机上,返回虚拟机的类型
    Golang操作结构体、Map转化为JSON
    PHP强制修改返回的状态码
    composer问题集锦
  • 原文地址:https://www.cnblogs.com/steben/p/3256312.html
Copyright © 2011-2022 走看看