How to write an xml file using C #

I am new to C # asp.net. I want to write an xml file in a C # file behind a file in my asp.net web application and pass this XML file as a string to a web service. Can anyone who can help me is very useful for my project. Thanks you

+3
source share
5 answers

As mentioned in fiver, you can use XmlDocument or the new simplified version of XDocument to create XML documents. Here is an example 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 only supported on .NET 3.5 and later.

+2
source

Xml XmlSerializer class:

:

    void SaveAsXmlToFile(object o, string fname)
    {
        XmlSerializer ser = new XmlSerializer(o.GetType());
        using (var f = File.Open(fname, FileMode.OpenOrCreate))
            ser.Serialize(f, o);
    }

DataContractSerializer , XmlSerializer.

:

:

    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();
    }

, Xml, xml, XmlDocument .., xml-, XmlWriter, .

+3

XMLDocument. CreateXXX XML.

, XML , Save(String) , .

+2

: XML #?

If you use .Net4, the XDocument class will work because .Net2 uses XmlDocument .

XDocument.ToString () returns XML as a string. For the XmlDocument class, you must use the XmlDocument.Save () method to save to the stream or TextWriter XmlDocument.OuterXml property .

Both examples on this question demonstrate how to output it as a string. You can use this to pass a string to your web service.

+1
source
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();
0
source

All Articles