在节点等方面在.net 2.0中创建xml文件的最佳方法是什么。我不认为我可以使用LINQ。任何代码示例或文章都会有所帮助。
答案 0 :(得分:4)
最好的办法是使用XmlTextWriter类。
这是一个非常基本的例子:
var writer = new XmlTextWriter("Foo.xml", Encoding.UTF8);
writer.WriteStartDocument();
writer.WriteStartElement("Foo");
writer.WriteAttributeString("hello", "world");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
这会给你:
<?xml version="1.0" encoding="utf-8"?>
<Foo hello="world" />
答案 1 :(得分:1)
以下是适用的代码段:
XmlTextWriter myXW = new XmlTextWriter(@"C:\NewXmlFile.xml", Encoding.UTF8)
myXW.WriteStartDocument();
myXW.WriteStartElement("Customers");
string strConn = myConnectionString;
OleDbConnection myConn = new OleDbConnection(strConn);
myConn.Open();
OleDbCommand myCMD = new OleDbCommand("select * from customers", myConn);
OleDbDataReader myRdr = myCMD.ExecuteReader();
while (myRdr.Read())
{
myXW.WriteStartElement("Customer");
myXW.WriteAttributeString("id", myRdr.GetString(0));
myXW.WriteElementString("companyname", myRdr.GetString(1));
myXW.WriteElementString("contactname", myRdr.GetString(2));
myXW.WriteElementString("contactname", myRdr.GetString(3));
myXW.WriteElementString("address", myRdr.GetString(4));
myXW.WriteElementString("city", myRdr.GetString(5));
myXW.WriteElementString("country", myRdr.GetString(8));
myXW.WriteElementString("phone", myRdr.GetString(9));
myXW.WriteElementString("fax", myRdr.GetString(10));
myXW.WriteEndElement();
}
myXW.WriteEndElement();
myXW.WriteEndDocument();
myXW.Flush();
myXW.Close();