Search code examples
c#xmlxmldocumentxmlreader

how to load data from XML file directly, instead of creating XML file by tring builder


I am working on StringBuilder to create XML document. I want to give directly input as XML file and get the data from it, instead of building the xml file.

           string namespaceUri = "NamespaceURI";
           System.Text.StringBuilder content = new StringBuilder();
           string First = "Hello World.This is Fisrt field";
           content.AppendFormat("<{0} xmlns=\"{1}\">", "rootelementname", namespaceUri);
           content.AppendFormat("<{0} xmlns=\"{1}\">{2}</{0}>", "first", namespaceUri, First);
           content.AppendFormat("</{0}>", "rootelementname");
           string data = content.ToString();

outputXML file created using this as follows

    <rootelementname xmlns="namespaceUri">
        <first>Hello World.This is Fisrt field</first>            
    </rootelementname>

if i have above xml file directly,underpath "E:\abcd\source.xml how can i load that source.xml into "data" variable directly.

Please share your thoughts on this.

Thank you


Solution

  • You can try the following:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(@"E:\abcd\source.xml");
    
    string data = xmlDoc.OuterXml;
    

    The above is just a sample, in your code please handle exceptions accordingly.