Coding Practice for F#

后端 未结 4 1175
礼貌的吻别
礼貌的吻别 2021-02-04 10:44

I have been dabbling with F# in Visual Studio 2010. I am a developer with more code/architecture design experience in object-oriented languages such as C# and Java.

T

4条回答
  •  感动是毒
    2021-02-04 11:27

    I have also recently needed to transform an XSL to an XML file. This is the F# I used to do this.

    Has some interesting quirks with using the .net methods.

    (* Transforms an XML document given an XSLT. *)
    
    open System.IO
    open System.Text
    open System.Xml
    open System.Xml.Xsl
    
    let path = @"C:\\XSL\\"
    
    let file_xml = path + "test.xml"
    let file_xsl = path + "xml-to-xhtml.xsl"
    
    (* Compile XSL file to allow transforms *)
    let compile_xsl (xsl_file:string) = new XslCompiledTransform() |> (fun compiled -> compiled.Load(xsl_file); compiled)
    let load_xml (xml_file:string) = new XmlDocument() |> (fun doc -> doc.Load(xml_file); doc)
    
    (* Transform an Xml document given an XSL (compiled *)
    let transform (xsl_file:string) (xml_file:string) = 
          new MemoryStream()
            |> (fun mem -> (compile_xsl xsl_file).Transform((load_xml xml_file), new XmlTextWriter(mem, Encoding.UTF8)); mem)
            |> (fun mem -> mem.Position <- (int64)0; mem.ToArray())
    
    (* Return an Xml fo document that has been transformed *)
    transform file_xsl file_xml
        |> (fun bytes -> File.WriteAllBytes(path + "out.html", bytes))
    

提交回复
热议问题