本节内容:
asp.net读取、写入xml文件。
首先,引入命令空间:
操作示例:
//1,读取xml
public static void savexml()
{
xmldoc.Save(lujing);
}
//2,保存xml
public static bool updatexml(string id,string txt,string url ,string src)
{
connxml();
XmlNodeList nodelist = xmldoc.SelectSingleNode("quanju").ChildNodes;
foreach (XmlNode xn in nodelist)
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("id") == id)
{
XmlNodeList nls = xe.ChildNodes;
foreach (XmlNode xn1 in nls)
{
XmlElement xe2 = (XmlElement)xn1;
if (xe2.Name == "text")
{
xe2.InnerText =txt;
continue;
}
}
XmlNodeList nls1 = xe.ChildNodes;
foreach (XmlNode xn1 in nls1)
{
XmlElement xe2 = (XmlElement)xn1;
if (xe2.Name == "url")
{
xe2.InnerText = url;
continue;
}
}
XmlNodeList nls2 = xe.ChildNodes;
foreach (XmlNode xn1 in nls2)
{
XmlElement xe2 = (XmlElement)xn1;
if (xe2.Name == "src")
{
xe2.InnerText = src;
continue;
}
}
savexml();
return true;
}
}
savexml();
return false;
}
//3,修改xml中数据
public static bool addxml(string id ,string type, string rootsub, string[] creArr,string[] setArr)
{
try
{
connxml();
XmlNode root = xmldoc.SelectSingleNode("quanju");
XmlElement xe1 = xmldoc.CreateElement(rootsub);
xe1.SetAttribute(type, id);
for (int i = 0; i < creArr.Length; i++)
{
XmlElement xesub1 = xmldoc.CreateElement(creArr[i]);
xesub1.InnerXml = setArr[i];
xe1.AppendChild(xesub1);
}
root.AppendChild(xe1);
savexml();
}
catch (Exception e)
{
return false;
}
finally
{
}
return true;
}
//4,添加xml中字段
public static bool delxml(string type,string val)
{
try
{
connxml();
XmlNodeList nodelist = xmldoc.SelectSingleNode("quanju").ChildNodes;
foreach (XmlNode xn in nodelist)
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute(type) == val)
{
xe.RemoveAll();
}
}
savexml();
}
catch (Exception e)
{
return false;
}
return true;
}