日期:2014-05-18  浏览次数:20840 次

用C#怎样向XML文件中写数据例子
各位高手帮帮忙!!!!谢谢~~~

------解决方案--------------------
看MSDN...
static void WriteQuote(XmlWriter writer, string symbol,
double price, double change, long volume)
{
writer.WriteStartElement( "Stock ");
writer.WriteAttributeString( "Symbol ", symbol);
writer.WriteElementString( "Price ", XmlConvert.ToString(price));
writer.WriteElementString( "Change ", XmlConvert.ToString(change));
writer.WriteElementString( "Volume ", XmlConvert.ToString(volume));
writer.WriteEndElement();
}

public static void Main(){
XmlTextWriter writer = new XmlTextWriter(Console.Out);
writer.Formatting = Formatting.Indented;
WriteQuote(writer, "MSFT ", 74.125, 5.89, 69020000);
writer.Close();
}
输出:
<Stock Symbol= "MSFT ">
<Price> 74.125 </Price>
<Change> 5.89 </Change>
<Volume> 69020000 </Volume>
</Stock>

------解决方案--------------------
想写数据非常容易,难的是查找之后修改,删除..

给个写的
private void Page_Load(object sender, System.EventArgs e)
{
string FileName = Server.MapPath( "phone.xml ");
XmlTextWriter objXmlTextWriter = new XmlTextWriter(FileName, null);

objXmlTextWriter.Formatting = Formatting.Indented;
objXmlTextWriter.Indentation = 6;

objXmlTextWriter.WriteStartDocument();

objXmlTextWriter.WriteStartElement( " ", "PhoneBook ", " ");

objXmlTextWriter.WriteStartElement( " ", "Name ", " ");
objXmlTextWriter.WriteString( "加菲尔德 ");
objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteStartElement( " ", "Number ", " ");
objXmlTextWriter.WriteString( "5555555 ");
objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteStartElement( " ", "City ", " ");
objXmlTextWriter.WriteString( "纽约 ");
objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteStartElement( " ", "DateOfBirth ", " ");
objXmlTextWriter.WriteString( "26/10/1978 ");
objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteEndElement();
objXmlTextWriter.WriteEndDocument();

objXmlTextWriter.Flush();

objXmlTextWriter.Close();
}