XML文件内容:
<?xml version="1.0" encoding="utf-8"?> <roottest> <UserInfo> <userid>100000</userid> <username>admin100000</username> <userpwd>123456</userpwd> </UserInfo> <UserInfo> <userid>100001</userid> <username>admin100001</username> <userpwd>123456</userpwd> </UserInfo> <reportinfo> <![CDATA[<?xml version="1.0" encoding="utf-8"?> <testRequest xmlns="http://www.test.com/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <classinfo> <classid>1000</classid> <classname>一年级</classname> </classinfo> </testRequest> ]]> </reportinfo> </roottest>
XML文件写入方法一:
string m_strFilePath = "C:\\Program Files" + @"\test1.xml";
XmlTextWriter xmlwriter = new XmlTextWriter(m_strFilePath, Encoding.UTF8);
xmlwriter.Formatting = Formatting.Indented;
xmlwriter.WriteStartDocument();
xmlwriter.WriteStartElement("roottest");
for (int i = 100000; i < 100002; i++)
{
xmlwriter.WriteStartElement("UserInfo");
xmlwriter.WriteElementString("userid", i.ToString());
xmlwriter.WriteElementString("username", "admin" + i.ToString());
xmlwriter.WriteElementString("userpwd", "123456");
xmlwriter.WriteEndElement();
}
StringBuilder datacontent = new StringBuilder("");
datacontent.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
datacontent.Append("<testRequest xmlns=\"http://www.test.com/test\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
datacontent.Append("<classinfo>");
datacontent.AppendFormat("<classid>{0}</classid>", "1000");
datacontent.AppendFormat("<classname>{0}</classname>", "一年级");
datacontent.Append("</classinfo>");
datacontent.Append("</testRequest>");
xmlwriter.WriteStartElement("reportinfo");
xmlwriter.WriteCData(datacontent.ToString());//写入<![CDATA[中内容
xmlwriter.WriteEndElement();
xmlwriter.WriteEndElement();
xmlwriter.WriteEndDocument();
xmlwriter.Flush();
xmlwriter.Close();
XML文件内容:
<?xml version="1.0" encoding="utf-8"?> <testRequest xmlns="http://www.test.com/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <classinfo> <classid>1000</classid> <classname>一年级</classname> </classinfo> </testRequest>
XML写入方法二:
XmlDocument doc = new XmlDocument();
XmlNode declare = doc.CreateXmlDeclaration("1.0", "utf-8", "");
doc.AppendChild(declare);
XmlElement root = doc.CreateElement("testRequest");
root.SetAttribute("xmlns", "http://www.test.com/test");
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
doc.AppendChild(root);
XmlElement classinfo = doc.CreateElement("classinfo");
XmlElement classid = doc.CreateElement("classid");
classid.InnerText = "1000";
XmlElement classname = doc.CreateElement("classname");
classname.InnerText = "一年级";
classinfo.AppendChild(classid);
classinfo.AppendChild(classname);
root.AppendChild(classinfo);
doc.Save("C:\\Program Files" + @"\test2.xml");