C#-XML文件提取字符串+字符串存为XML文件+创建XML(自定义节点)文件+读取节点内容
-
一、将字符串写入xml文件(并保存)
写入:
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(“xmlstring”);
保存:
xdoc.Save(“pathsave.xml”)二、将xml文件赋值到字符串
读取xml文件:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(“pathload.xml”);
返回字符串:
xdoc.InnerXml :xmlstring是你的xml字符串三、根据节点创建XML文件
XmlTextWriter myXmlTextWriter = new XmlTextWriter(System.Web.HttpContext.Current.Server.MapPath(path), System.Text.Encoding.UTF8);myXmlTextWriter.Formatting = Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteStartElement(“Respond”); //根节点
myXmlTextWriter.WriteStartElement(“head”); //head节点
myXmlTextWriter.WriteElementString(“Return_Code”, 数据值); //head节点的内容节点
myXmlTextWriter.WriteElementString(“Return_Desc”, 数据值);
myXmlTextWriter.WriteElementString(“Return_Msg”, 数据值);myXmlTextWriter.WriteEndElement(); //head节点结束
myXmlTextWriter.WriteEndElement();//根节点结束myXmlTextWriter.Flush();
myXmlTextWriter.Close();四、按照节点读取xml文件
1.先创建Respond实体类:(string * get;set;)
内容包括
sting Return_code,Return_msg,Return_desc/* * 获取RespondLog日志信息 * */ public List<Respond> GetRespondLogXML(string path) { XmlDocument doc = new XmlDocument(); doc.Load(System.Web.HttpContext.Current.Server.MapPath(path)); XmlNode xn = doc.SelectSingleNode("Respond"); XmlNodeList xnl = xn.ChildNodes; List<Respond> logList = new List<Respond>(); foreach (XmlNode xn1 in xnl) { Respond log = new Respond(); XmlElement xe = (XmlElement)xn1; XmlNodeList xnl0 = xe.ChildNodes; log.Return_code = xnl0.Item(0).InnerText; log.Return_msg = xnl0.Item(1).InnerText; log.Return_desc = xnl0.Item(2).InnerText; logList.Add(log); } return logList; }
//读取Respond.xml文件信息
List logList = new List();
logList = GetRespondLogXML(Respondlog);
Return_code = logList[0].Return_code;
Return_msg = logList[0].Return_msg;
Return_desc = logList[0].Return_desc;
版权声明:本文为博主原创文章,未经博主允许不得转载。