hubFS: THE place for F#

. . . are you on The Hub?
Welcome to hubFS: THE place for F# Sign in | Join | Help
in Search

indent XML

Last post 07-10-2008, 5:18 by Robert. 3 replies.
Sort Posts: Previous Next
  •  07-09-2008, 16:38 6343

    indent XML

    I would like to write a XML string to a file, with indentation.
    I tried the following:

    let xw = new XmlTextWriter(file, Text.Encoding.Unicode)
                xw.Formatting <- Formatting.Indented;
                xw.WriteString(xml)
  •  07-10-2008, 0:03 6347 in reply to 6343

    Re: indent XML

    The problem with your code is xw is not in scope when you try and use it. You want to say something like:

    #light
    open System.IO
    open System.Xml
    open System.Text
    let main() =
        let file = File.Create("c:\\out.xml")
        let xml = "<xml />"
        let xw = new XmlTextWriter(file, Encoding.Unicode)
        xw.Formatting <- Formatting.Indented;
        xw.WriteString(xml)
       
    do main()


    Robert Pickering, MVP
    http://strangelights.com
  •  07-10-2008, 3:02 6349 in reply to 6347

    Re: indent XML

    ok.  It was fault because I didn't indent the code properly in my post.  But my F# script is correctly indented and the problem persists.

    Thanks.
  •  07-10-2008, 5:18 6350 in reply to 6349

    Re: indent XML

    Arrh, okay. There's a couple of problems with the code I posted. You need to close both the file and the text writer to ensure they are disposed. Also the text writer is designed to be used to write elements indivdually. The easiest way to correct this is to pass by the DOM:

    #light
    open System.IO
    open System.Xml
    open System.Text
    let main() =
        use file = File.Create(@"C:\Documents and Settings\rpickering\My Documents\Visual Studio 2008\Projects\TestWriteXML\test.xml")
        let xml = "<xml><toto>tete</toto></xml>"
        let doc = new XmlDocument()
        doc.LoadXml(xml)
        use xw = new XmlTextWriter(file, Encoding.UTF8)
        xw.Formatting <- Formatting.Indented;
        doc.WriteTo(xw)
       
    do main()


    Robert Pickering, MVP
    http://strangelights.com
View as RSS news feed in XML
Powered by Community Server, by Telligent Systems