Achieving XML format in C#
How can i achieve a format like this in C#?
suppose this is the output:
<Region id="1" name="Africa"/>
so far this is my C# code:
using (XmlWriter xml_writer = XmlWriter.Create(str_builder))
{
xml_writer.WriteStartDocument();
xml_writer.WriteStartElement("RegionList");
foreach (var get_regions in qdb_conn.Regions())
{
xml_write开发者_如何学运维r.WriteStartElement("Region");
xml_writer.WriteEndElement();
}
xml_writer.WriteEndElement();
xml_writer.WriteEndDocument();
}
Unless you really have to use XmlWriter
, I simply wouldn't. I'd use LINQ to XML instead:
XElement region = new XElement("Region",
new XAttribute("id", 1),
new XAttribute("name", "Africa"));
Job done - you can then write that to whatever you want. Having said that, it should be easy to get your existing code to work. Just change the loop to something like:
foreach (var get_regions in qdb_conn.Regions())
{
xml_writer.WriteStartElement("Region");
xml_writer.WriteAttributeString("id", XmlConvert.ToString(get_regions.Id));
xml_writer.WriteAttributeString("name", get_regions.Name);
xml_writer.WriteEndElement();
}
精彩评论