-1

I've xml data inside a local variable xml of type XMLDocument I wish to save the xml data as it is into a local file.

I've tried something like System.IO.File.WriteAllText(@"C:\MyProfile\OutOut.txt", xml.ToString()); but doesn't work.

Can someone let me know how to proceed for this?

Also let me now if any additional data is needed.

Thanks.

**Update: ** The above task was accomplished by using XmlDocument.Save(FilePath); now just a small update to the questio is like :

If I have to save only a specific parent node along with it's child nodes, how do I proceed

Sample xml file

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Master Name="Accounts">
<Employee>
    <Section>
      <Details>
        <Name="abc" ID="68" PF="9999" />
      </Details>
      <Department DeptId="12" />
    </Section>
    <Section>
      <Details>
        <Name="xyz" ID="69" PF="9999"  />
      </Details>
      <Department DeptId="13" />
    </Section>
</Employee>
</Master>

Only Node <Employee> and it's children.

m_beta
  • 132
  • 15
  • 1
    Have you looked to see if perhaps the [`XmlDocument` class](https://learn.microsoft.com/dotnet/api/system.xml.xmldocument) provides a method that meets your needs? – Lance U. Matthews Mar 19 '20 at 04:56
  • Or search the internet for something like *xmldocument to string c#* – Flydog57 Mar 19 '20 at 05:04
  • 1
    Does this answer your question? [How do I write an XML string to a file?](https://stackoverflow.com/questions/590881/how-do-i-write-an-xml-string-to-a-file) – Louis Go Mar 19 '20 at 05:06
  • 1
    XmlDocument.Save() - Use the File name as ".txt" – Prateek Shrivastava Mar 19 '20 at 05:11
  • The ToString method is the correct solution. Why doesn't it work. I suspect there are no carriage returns so every thing is on one line. Xml doesn't require the return so what you have is correct. – jdweng Mar 19 '20 at 06:16
  • @BACON Thanks for highlighting. Got this `XmlDocument.Save("FileName");` and it works but I was just wondering if there's a way to save data from a specific parent node including all it's child node. I saw this `XMLDocument.SelectNodes()` but I'm not getting the `xpath` correctly. – m_beta Mar 19 '20 at 06:57

1 Answers1

0

This code converts XmlDocument to text:

using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
    xmlDoc.WriteTo(xmlTextWriter);
    xmlTextWriter.Flush();
    return stringWriter.GetStringBuilder().ToString();
}
Dilshod K
  • 2,924
  • 1
  • 13
  • 46