/// <summary>
/// 自动创建XML 文件
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="xmlName">XML名称</param>
public void createXml(string xmlName)
{
// Create the file and writer.
FileStream fs = new FileStream(xmlName, FileMode.Create);
XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);
// Start the document.
w.WriteStartDocument();
w.WriteStartElement("AreaData");//开始标签(根目录)
// Write a AreaItem.
w.WriteStartElement("AreaItem ");
w.WriteAttributeString("AreaID", "29");//属性名、属性值
w.WriteAttributeString("dx", "3998");
w.WriteAttributeString("zx", "9912");
//w.WriteElementString("productName", "Blue China Tea Pot");//创建元素
w.WriteEndElement();
// Write another AreaItem.
w.WriteStartElement("AreaItem ");
w.WriteAttributeString("AreaID", "999");
w.WriteAttributeString("dx", "4545");
w.WriteAttributeString("zx", "4588");
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();
fs.Dispose();
Console.WriteLine("Document created. " +
"Press Enter to read the document.");
Console.ReadLine();
fs = new FileStream("products.xml", FileMode.Open);
XmlTextReader r = new XmlTextReader(fs);
// Read all nodes.
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
{
Console.WriteLine();
Console.WriteLine("<" + r.Name + ">");
if (r.HasAttributes)
{
for (int i = 0; i < r.AttributeCount; i++)
{
Console.WriteLine("\tATTRIBUTE: " +
r.GetAttribute(i));
}
}
}
else if (r.NodeType == XmlNodeType.Text)
{
Console.WriteLine("\tVALUE: " + r.Value);
}
}
Console.ReadLine();
fs.Close();
fs.Dispose();//释放资源
}
转载于:https://blog.51cto.com/fengbo1983/500168