美文网首页
C# XML读取

C# XML读取

作者: 假装我不帅 | 来源:发表于2019-07-15 10:17 被阅读0次
            /// <summary>
            /// 读取XML文件中的指定元素名称的指定属性值
            /// </summary>
            /// <param name="xmlPath"></param>
            /// <param name="ElmentName"></param>
            /// <param name="AttributeName"></param>
            /// <returns></returns>
            /*
            XML格式如下
           <FW Key="141101"  Mapping="6"/>
           调用方法如下:
           GeElementString(路径,FW,Key/Mapping)
            */
            public static string GetElementString(string xmlPath, string ElmentName, string 
    AttributeName)
            {
                XmlTextReader xmlRd = new XmlTextReader(xmlPath);
                string strResult = "";
                try
                {
                    while (xmlRd.Read())
                    {
                        if (xmlRd.NodeType == XmlNodeType.Element && 
    xmlRd.Name.Equals(ElmentName))
                        {
                            strResult = xmlRd.GetAttribute(AttributeName);
                        }
                    }
                    xmlRd.Close();
                }
                catch (Exception)
                {
                }
                finally
                {
                    xmlRd.Close();
                }
                return strResult;
            }
            
            /// <summary>
            /// 写入指定XML中指定元素名称内的属性值
            /// </summary>
            /// <param name="xmlPath"></param>
            /// <param name="ElmentName"></param>
            /// <param name="AttributeName"></param>
            /// <param name="Value"></param>
            public static void WriteElementString(string xmlPath, string ElmentName, string 
    AttributeName, string Value)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                XmlNodeList node = xmlDoc.GetElementsByTagName(ElmentName);
                foreach (XmlNode node1 in node)
                {
                    node1.Attributes[AttributeName].Value = Value;
                }
                xmlDoc.Save(xmlPath);
            }
    

    相关文章

      网友评论

          本文标题:C# XML读取

          本文链接:https://www.haomeiwen.com/subject/fwugkctx.html