C# xml 读xml、写xml、Xpath、Xml to Linq、xml添加节点 xml修改节点

 

     #region 增、删、改操做==============================================
        
        /// <summary>
        /// 追加节点
        /// </summary>
        /// <param name="filePath">XML文档绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <param name="xmlNode">XmlNode节点</param>
        /// <returns></returns>
        public static bool AppendChild(string filePath, string xPath, XmlNode xmlNode)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xn = doc.SelectSingleNode(xPath);
                XmlNode n = doc.ImportNode(xmlNode, true);
                xn.AppendChild(n);
                doc.Save(filePath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 从XML文档中读取节点追加到另外一个XML文档中
        /// </summary>
        /// <param name="filePath">须要读取的XML文档绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <param name="toFilePath">被追加节点的XML文档绝对路径</param>
        /// <param name="toXPath">范例: @"Skill/First/SkillItem"</param>
        /// <returns></returns>
        public static bool AppendChild(string filePath, string xPath, string toFilePath, string toXPath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(toFilePath);
                XmlNode xn = doc.SelectSingleNode(toXPath);

                XmlNodeList xnList = ReadNodes(filePath, xPath);
                if (xnList != null)
                {
                    foreach (XmlElement xe in xnList)
                    {
                        XmlNode n = doc.ImportNode(xe, true);
                        xn.AppendChild(n);
                    }
                    doc.Save(toFilePath);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 修改节点的InnerText的值
        /// </summary>
        /// <param name="filePath">XML文件绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <param name="value">节点的值</param>
        /// <returns></returns>
        public static bool UpdateNodeInnerText(string filePath, string xPath, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xn = doc.SelectSingleNode(xPath);
                XmlElement xe = (XmlElement)xn;
                xe.InnerText = value;
                doc.Save(filePath);
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 读取XML文档
        /// </summary>
        /// <param name="filePath">XML文件绝对路径</param>
        /// <returns></returns>
        public static XmlDocument LoadXmlDoc(string filePath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                return doc;
            }
            catch
            {
                return null;
            }
        }
        #endregion 增、删、改操做

        #region 扩展方法===================================================
        /// <summary>
        /// 读取XML的全部子节点
        /// </summary>
        /// <param name="filePath">XML文件绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <returns></returns>
        public static XmlNodeList ReadNodes(string filePath, string xPath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xn = doc.SelectSingleNode(xPath);
                XmlNodeList xnList = xn.ChildNodes;  //获得该节点的子节点
                return xnList;
            }
            catch
            {
                return null;
            }
        }

        #endregion 扩展方法
扩                   展

 

 #region XDocument
            //建立XDocument
            XDocument xdoc2 = new XDocument();
            XElement xel1= new XElement("AA",new XAttribute("mark","mark"));
            xel1.Add(new XElement("AA1","2"));
            xel1.Add(new XElement("AA2", "3"));
            XElement xel2 = new XElement("AA");
            xel2.Add(new XElement("AA1", "2"));
            xel2.Add(new XElement("AA2", "3"));
            xel2.Add(new XElement("AAA1", new XElement("AAA1","4")));
            XElement xel = new XElement("A");
            xel.Add(xel2, xel1);
            xdoc2.Add(xel);

            ///循环XDocument 
            foreach (XElement xElement in xdoc2.Document.Root.Elements())
            {
                //根据节点名称获取值
                string text=xElement.Element("AA1").Value;
                //string text2 = xElement.Element("AAA1").Element("AAA1").Value;
                //修改节点
                xElement.SetElementValue("AA1", "AAA2");
                //添加属性
                xElement.SetAttributeValue("name", "name");
                //设置值
                xElement.Element("AA1").SetValue("");
            }
            #endregion

            #region XmlDocument
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("D://Pro//EGP410_5//Test//XMLFile1.xml");
            //循环XmlDocument
            XmlNodeList xmlNode= xmlDoc.DocumentElement.ChildNodes;
            foreach (XmlNode item in xmlNode)
            {
            }
            //查询
            string str = xmlDoc.DocumentElement.SelectSingleNode("DTrue").InnerText;
            str = xmlDoc.DocumentElement.SelectSingleNode("/Result/DTrue").InnerText;
            //修改
            xmlDoc.DocumentElement.SelectSingleNode("DTrue").InnerText = "DTrue";
            //获取属性
            str = xmlDoc.DocumentElement.GetAttribute("mark");
            //修改属性
            xmlDoc.DocumentElement.SetAttribute("mark", "1543286313566");
            //保存。
            xmlDoc.Save("D://Pro//EGP410_5//Test//XMLFile1.xml");

            #endregion
View Code  XDocument和XmlDocument的建立 修改 查询 属性 循环等操做

xml的读javascript

XElement xele1 = XElement.Load(Path);  //根据路径获取xml元素html

XElement xele2 = XElement.Parse("");      //根据字符串获取xml元素java

 

XmlDocument doc = new XmlDocument();node

doc.LoadXml(xele1.ToString());        //根据字符串获取xml文档ide

doc.Load(Path);                 //根据路径获取xml文档ui

xml的取xpathspa

  

 XDocument doc = XDocument.Load(Path);
 XElement root = doc.Element("DATASET").Element("BUYER_NAME");code

 string text = xnode.InnerText;           //获取值(方式一)server

 

 XmlNode node=doc2.SelectSingleNode("//DATASET/BUYER_NAME");     //获取单个xmlnode 不用循环xml

  XmlNodeList nodes = doc.SelectNodes("//A/A01/A0101");   // 双斜线表示不从根目录取(获取多个xmlnode 因此要采用循环)

  foreach (XmlNode de in nodes)
  {
        var dsd = de.InnerText;      //获取值(方式二)
  }

  xml的写包括写入备注 (linq to xml)

        public static void CreateXmlByLink()
        {
            XDocument xdoc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XComment("提示"),
                new XElement("root",
                    new XElement("A",
                        new XElement("A01",
                        new XElement("A0101", "货物A0101"),
                        new XComment("提示"), 
                        new XAttribute("V1", "1"),
                        new XElement("A0102", "货物A0102"),
                         new XElement("A0103",
                            new XAttribute("V1", "1"),
                             new XElement("A010301",new XAttribute("V1", "1"), "货物A010301"),
                             new XElement("A010302", "货物A010302")
                             )
                        ),
                        new XElement("A01",
                        new XElement("A0101", "货物A0101"),
                        new XElement("A0102", "货物A0102"),
                         new XElement("A0103",
                             new XElement("A010301", "货物A010301"),
                             new XElement("A010302", "货物A010302")
                             )
                             )
                        ),



                                    new XElement("B",
                        new XElement("A01",
                        new XElement("A0101", "货物A0101"),
                        new XElement("A0102", "货物A0102"),
                         new XElement("A0103",
                             new XElement("A010301", "货物A010301"),
                             new XElement("A010302", "货物A010302")
                             )
                        ),
                        new XElement("A01",
                        new XElement("A0101", "货物A0101"),     
                        new XElement("A0102", "货物A0102"),
                         new XElement("A0103",
                             new XElement("A010301", "货物A010301"),
                             new XElement("A010302", "货物A010302")
                             )
                             )
                        ),


                             new XElement("C",
                        new XElement("A01",
                        new XElement("A0101", "货物A0101"),
                        new XElement("A0102", "货物A0102"),
                         new XElement("A0103",
                             new XElement("A010301", "货物A010301"),
                             new XElement("A010302", "货物A010302")
                             )
                        ),
                        new XElement("A01",
                        new XElement("A0101", "货物A0101"),
                        new XElement("A0102", "货物A0102"),
                         new XElement("A0103",
                             new XElement("A010301", "货物A010301"),
                             new XElement("A010302", "货物A010302")
                             )
                             )
                        )
                    )
            );
            xdoc.Save(Path);
        }
View Code

 

添加节点

 

XmlNode node= doc.SelectNodes("//A/A01/A0101")[0];     //修改/添加 路径下   的第一个节点 

XmlElement no = doc.CreateElement("newNode");
no.InnerText = "新增节点1";
node.AppendChild(no);  //新增

修改、删除xml节点

foreach (XmlNode item in node)
{
XmlElement xe = (XmlElement)item ;
if (xe.GetAttribute("A") == "A01")
{
xe.SetAttribute("A","A");  //修改

xe.Remove("A");  //修改
}
}

 xml 映射到页面table(参照http://www.w3school.com.cn/tiy/t.asp?f=xmle_display_table_1)

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
        .a {
            border: 1px solid red;
        }
    </style>
    <script type="text/javascript">
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "test.xml", false);
        xmlhttp.send();

        xmlDoc = xmlhttp.responseXML;

        var html = "<table border='1' class=\"a\" style=\"width:100px;height:20px\">";
        var x = xmlDoc.getElementsByTagName("CD");
        for (i = 0; i < x.length; i++) {
            html = html + "</td><td>";
            html = html + x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
            html = html + "</td><td>";
            html = html + x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;

            html = html + "</td><td>";
            html = html + x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue;
            html = html + "</td></tr>";
        }
        html = html + "</table>";
        document.write(html)
    </script>
</head>
<body>
</body>
</html>
View Code