我正在尝试使用Microsoft Visual Studio 2010和MSSQL Server使用ASP.Net C#做一个Banner Rotator。我已经将那些记录在数据库中的项目写入了XML。但是,我无法给出WriteStartElement( “属性”)。
XML代码:
XmlTextWriter xmlyazici = new XmlTextWriter(Server.MapPath("banner.xml"), Encoding.UTF8);
xmlyazici.WriteStartDocument();
SqlConnection baglanti = new SqlConnection(ConfigurationManager.ConnectionStrings["baglan"].ConnectionString);
baglanti.Open();
string sql = "SELECT TOP 6 ID,RESIM,URL,DURATION FROM REKLAMLAR ORDER BY REKLAMLAR.ID DESC";
SqlCommand komut = new SqlCommand(sql, baglanti);
SqlDataReader dr = komut.ExecuteReader();
xmlyazici.WriteStartElement("banner"); // aşağıdaki örnekteki gibi özellikler atamak istiyorum(Yapmaya Çalıştığım xml Çıktı Kısmı gibi).
while (dr.Read())
{
xmlyazici.WriteStartElement("item");
xmlyazici.WriteElementString("path", "images/" + dr.GetString(1) + "");
xmlyazici.WriteElementString("link", "" + dr.GetString(2) + "");
xmlyazici.WriteElementString("bar_color", "0xffffff");
xmlyazici.WriteElementString("bar_transparency", "40");
xmlyazici.WriteElementString("caption_color", "0xffffff");
xmlyazici.WriteElementString("caption_transparency", "60");
xmlyazici.WriteElementString("stroke_color", "0xffffff");
xmlyazici.WriteElementString("stroke_transparency", "60");
xmlyazici.WriteElementString("slideshowTime", "" + dr.GetString(3) + "");
xmlyazici.WriteEndElement();
}
dr.Close();
baglanti.Close();
xmlyazici.WriteEndElement();
xmlyazici.WriteEndDocument();
xmlyazici.Flush();
xmlyazici.Close();
上层代码的XML结果:
<banner>
<item>
<path>images/72815305878.jpg</path>
<link>http://www.xxxxxxx.com/default.aspx</link>
<bar_color>0xffffff</bar_color>
<bar_transparency>40</bar_transparency>
<caption_color>0xffffff</caption_color>
<caption_transparency>60</caption_transparency>
<stroke_color>0xffffff</stroke_color>
<stroke_transparency>60</stroke_transparency>
<slideshowTime>20</slideshowTime>
</item>
</banner>
我想做的事情:
***<banner width = "" height = ""
startWith = "1"
random = "false">***
<item>
<path>images/72815305878.jpg</path>
<link>http://www.xxxxx.com/default.aspx</link>
<bar_color>0xffffff</bar_color>
<bar_transparency>40</bar_transparency>
<caption_color>0xffffff</caption_color>
<caption_transparency>60</caption_transparency>
<stroke_color>0xffffff</stroke_color>
<stroke_transparency>60</stroke_transparency>
<slideshowTime>20</slideshowTime>
</item>
</banner>
答案 0 :(得分:1)
我会使用XmlDocument
和XmlNode
类。这样您就可以向XmlNodes添加属性,然后将XmlNodes添加到文档中:
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("banner");
((XmlElement)root).SetAttribute("attribute-name", "attribute value");
doc.AppendChild(root);
希望这有帮助。
答案 1 :(得分:0)
如果我理解正确,您需要在横幅广告代码中添加属性。
XmlWriter.WriteAttributeString()
方法就是这么做的。 你打电话后
xmlyazici.WriteStartElement("banner");
使用以下方法:
xmlyazici.WriteAttributeString("width", "");
xmlyazici.WriteAttributeString("height", "");
xmlyazici.WriteAttributeString("startWith", "1");
xmlyazici.WriteAttributeString("random", "false");