Reputation: 299
I am newer person in c# asp.net . I want to write xml file in c# code behind file in my asp.net web application and pass this xml file as a string to a webservice . Can any one able to help me its will very useful for my project . Thank you
Upvotes: 3
Views: 27989
Reputation: 3430
As "fiver" had mentioned you could use the XmlDocument or the new simplified version XDocument for creating XML Documents. Here's a sample code snippet from MSDN for creating XML documents and writing to a file.
XDocument doc = new XDocument(
new XElement("Root",
new XElement("Child", "content")
)
);
doc.Save("Root.xml");
This will write the following text to the xml file
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Child>content</Child>
</Root>
Note: XDocument is supported only on .NET framework 3.5 and above
Upvotes: 3
Reputation: 24182
You can serialize objects in Xml by using XmlSerializer
class:
Serializing to a file:
void SaveAsXmlToFile(object o, string fname)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
using (var f = File.Open(fname, FileMode.OpenOrCreate))
ser.Serialize(f, o);
}
You can also use DataContractSerializer
class the same way as XmlSerializer
.
You can also serialize an object to a string, and return it:
Serializing to a string:
string ToXml(object o)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
ser.Serialize(sw, o);
return sb.ToString();
}
Also, if you need more control over produced Xml, you can use structured xml objects, like XmlDocument
and so on, or xml writing classes like XmlWriter
as denoted in other answers.
Upvotes: 3
Reputation: 19465
See this question: How can I build XML in C#?
If you're using .Net4 the XDocument class would work, for .Net2 use the XmlDocument.
The XDocument.ToString() directly returns the XML as a string. For the XmlDocument class you would use the XmlDocument.Save() method, to save to a stream or a TextWriter XmlDocument.OuterXml property.
Both examples on that question demonstrate how to output it as a string. You can use that to pass the string to your web service.
Upvotes: 1
Reputation: 5727
using System.Xml;
using System.Xml.Schema;
XmlTextWriter xtwFeed = new XmlTextWriter(Server.MapPath("rss.xml"), Encoding.UTF8);
xtwFeed.WriteStartDocument();
// The mandatory rss tag
xtwFeed.WriteStartElement("rss");
xtwFeed.WriteAttributeString("version", "2.0");
// Write all the tags like above and end all elements
xtwFeed.WriteEndElement();
xtwFeed.WriteEndDocument();
xtwFeed.Flush();
xtwFeed.Close();
Upvotes: 0
Reputation: 93000
You can use the XMLDocument class. It has various CreateXXX
methods for creating XML elements.
It seem you don't need to save the XML file, so you can use the Save(String)
method to serialize it to a string, when you are done.
Upvotes: 2