public string createXML()
{
StringBuilder sb = new StringBuilder();
XmlWriterSettings setting = new XmlWriterSettings();
setting.OmitXmlDeclaration = false;
setting.CheckCharacters = true;
setting.ConformanceLevel = ConformanceLevel.Auto;
XmlWriter xw = XmlWriter.Create(sb,setting);
xw.WriteStartDocument(true);
xw.WriteStartElement("班级");
xw.WriteStartElement("学生");
xw.WriteAttributeString("学号", "0443111241");
xw.WriteAttributeString("姓名", "张三");
xw.WriteStartElement("成绩");
xw.WriteAttributeString("语文", "90");
xw.WriteAttributeString("数学", "100");
xw.WriteAttributeString("英语", "95");
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteStartElement("学生");
xw.WriteAttributeString("学号", "044311121");
xw.WriteAttributeString("姓名", "李四");
xw.WriteStartElement("成绩");
xw.WriteAttributeString("语文", "100");
xw.WriteAttributeString("数学", "100");
xw.WriteAttributeString("英语", "95");
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteEndElement();
xw.WriteEndDocument();
xw.Close();
return sb.ToString();
}
生成的xml为:
<?xml version="1.0" encoding="utf-16" standalone="yes"?><班级><学生 学号="0443111241" 姓名="张三"><成绩 语文="90" 数学="100" 英语="95" /></学生><学生 学号="044311121" 姓名="李四"><成绩 语文="100" 数学="100" 英语="95" /></学生></班级>