xml


一.更新现有xml文件数据
1.保证原先xml的节点存在文本和数据库传递的数据有数据才行
public static void UpdateXmlInnerText(string xmlPath, string strSingleNode, DataRow dr)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;//忽略文档里面的注释
                                           //   XmlReader reader = XmlReader.Create( xmlPath, settings);
            Xmldoc.Load(xmlPath);
            XmlNodeList xnl = Xmldoc.SelectSingleNode("Request/Body/" + strSingleNode).ChildNodes;
            int i = 0;
            foreach (XmlNode xn in xnl)
            {
                // 将节点转换为元素,便于得到节点的属性值
                XmlElement xe = (XmlElement)xn;
                // 得到Type和ISBN两个属性的属性值
                //   bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
                //  bookModel.BookType = xe.GetAttribute("Type").ToString();
                // 得到Book节点的所有子节点
                XmlNodeList xnl0 = xe.ChildNodes;
                try
                {
                    string strDrItem = dr[i].ToString();
                    //保证原先xml的节点存在文本和数据库传递的数据有数据才行
                    if (xnl0.Item(0) != null)
                    {
                        if ((strDrItem != "") || ((strDrItem != null)))
                        {
                            xnl0.Item(0).InnerText = strDrItem;
                        }

                    }
                    else
                    {
                        // xnl0.Item(0).;
                    }

                }
                catch (Exception)
                {
                    xnl0.Item(0).InnerText = "";
                }

                ++i;

            }


            Xmldoc.Save(xmlPath);

        }

2.这个单纯改动text,不管空不空,好

   private static  void  GetXmlChildNodeText(string xmlPath,string strRootNode, string strParNode, string strSingleNode, DataRow dr)
        {
            Xmldoc.Load(xmlPath);
            XmlNodeList xnl = Xmldoc.SelectSingleNode(strRootNode+"/"+ strParNode+"/" + strSingleNode).ChildNodes;
            int i = 0;
            foreach (XmlNode xn in xnl)
            {                              
                xn.InnerText = dr[i].ToString();
                ++i;
            }
            Xmldoc.Save(xmlPath);
        }

 3.包含中文报错:An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll  Additional information: 给定编码中的字符无效。 第 7 行,位置 36。

解决方案:把xml文件另存为,选择utf-8保存。

原文地址:https://www.cnblogs.com/2186009311CFF/p/6434625.html