I am writing an interface in a Web service that returns XML output. The output is queried from a MS SQL database by calling stored procedure. While the stored procedure itself is not returning XML, and I don't have any control over it, I need to return the result set as XML.
Right now, I'm using XmlWriter. Is there an easier, elegant way to do this?
StringBuilder sbLog = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sbLog);
writer.WriteStartDocument();
writer.WriteStartElement("LogSet");
while (sqlRdr.Read())
{
writer.WriteStartElement("Log");
writer.WriteStartElement("EntryID");
writer.WriteValue(sqlRdr["EntryID"].ToString());
writer.WriteEndElement();
//and so on
Yeah XDocument
is probably a cleaner interface. It would look something like this:
var doc = new XDocument(
new XElement("LogSet",
new XElement("EntryID", sqlRdr["EntryID"].ToString()),
new XElement(...)
)
);
// save it to a file
doc.Save(pathToDoc);
// or just return it
return doc.ToString();
I'm not sure about it's elegance (I guess that partially depends on how many times you need to reproduce this sort of thing in your code), but I wrote an XmlDataReader a while back that converts tabular data in an IDataReader into an Xml result without the need to create a secondary document/string. As WebServices could return an XmlNode (rather than XmlReader) the second class XmlNodeFactory does that conversion.
Here is the Gist for XmlDataReader And for the XmlNodeFactory
Usage is something like:
[WebMethod]
public XmlNode GetFeaturedItems(string storeId)
{
var xmlReader = new XmlDataReader(
_db.GetFeaturedItems(storeId),
MyXmlNames.FeaturedItemsNamespace)
{
IncludeIndexField = false,
IncludeResultLevel = false,
RootElementName = "FeaturedItems",
RowElementNameFormat = "Item"
};
return XmlNodeFactory.Create(xmlReader);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.