c# 怎么使用XmlDocument

2025-02-25 00:51:31
推荐回答(2个)
回答1:

---给你几个函数吧
using System.Xml;

public void WriteXml(string filename)
{
//生成ProgramList.xml
XmlDocument ProgramListXmlDoc = new XmlDocument();
XmlDeclaration xmldecl = ProgramListXmlDoc.CreateXmlDeclaration("1.0", "gb2312", null);
ProgramListXmlDoc.AppendChild(xmldecl);

//加入一个根元素
XmlElement xmlelem = ProgramListXmlDoc.CreateElement("", "root", "");
XmlNode root = ProgramListXmlDoc.AppendChild(xmlelem);
xmlelem = ProgramListXmlDoc.CreateElement("sysoption");
XmlElement tmpelem = ProgramListXmlDoc.CreateElement("sc_server_ip");
tmpelem.InnerText = Sc_server_ip;
xmlelem.AppendChild(tmpelem);
tmpelem = ProgramListXmlDoc.CreateElement("device_type");
tmpelem.InnerText = Device_type;
xmlelem.AppendChild(tmpelem);
tmpelem = ProgramListXmlDoc.CreateElement("station_id");
tmpelem.InnerText = Station_id;
xmlelem.AppendChild(tmpelem);
tmpelem = ProgramListXmlDoc.CreateElement("serial_number");
tmpelem.InnerText = Serial_number;
xmlelem.AppendChild(tmpelem);

tmpelem = ProgramListXmlDoc.CreateElement("database_ip");
tmpelem.InnerText = database_ip;
xmlelem.AppendChild(tmpelem);

root.AppendChild(xmlelem);
ProgramListXmlDoc.Save(filename);
}

public void LoadXml(string filename)
{
try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(filename);
Sc_server_ip = xmldoc.SelectSingleNode("root/sysoption/sc_server_ip").InnerText.Trim();
Serial_number = xmldoc.SelectSingleNode("root/sysoption/serial_number").InnerText.Trim();
sc_server_ip = xmldoc.SelectSingleNode("root/sysoption/sc_server_ip").InnerText.Trim();
database_ip = xmldoc.SelectSingleNode("root/sysoption/database_ip").InnerText.Trim();
}
catch (Exception e)
{
}
}

回答2:

不是XmlDocument缺少using,你把代码贴出来吧,XmlDocument就在System.Xml这个命名空间内。