import kxml.xml;
char[][][]characters =
        [["April","Bubbly: I'm > Tam and <= Emily"],
        ["Tam O'Shanter","Burns: \"When chapman billies leave the street ...\""],
        ["Emily","Short & shrift"]];
void addChars(XmlNode root,char[][][]info) {
        auto remarks = new XmlNode("CharacterRemarks");
        root.addChild(remarks);
        foreach(set;info) {
                remarks.addChild((new XmlNode("Character")).setAttribute("name",set[0]).addCData(set[1]));
        }
}
void main() {
        auto root = new XmlNode("");
        root.addChild(new XmlPI("xml"));
        addChars(root,characters);
        std.stdio.writefln("%s",root.write);
}


//You need to use these units
uses
  Classes,
  Dialogs,
  XMLIntf,
  XMLDoc;

//..............................................

//This function creates the XML
function CreateXML(aNames, aRemarks: TStringList): string;
var
  XMLDoc: IXMLDocument;
  Root: IXMLNode;
  i: Integer;
begin
  //Input check
  if (aNames   = nil) or
     (aRemarks = nil) then
  begin
     Result:= '<CharacterRemarks />';
     Exit;
  end;

  //Creating the TXMLDocument instance
  XMLDoc:= TXMLDocument.Create(nil);

  //Activating the document
  XMLDoc.Active:= True;

  //Creating the Root element
  Root:= XMLDoc.AddChild('CharacterRemarks');

  //Creating the inner nodes
  for i:=0 to Min(aNames.Count, aRemarks.Count) - 1 do
  with Root.AddChild('Character') do
  begin
    Attributes['name']:= aNames[i];
    Text:= aRemarks[i];
  end;

  //Outputting the XML as a string
  Result:= XMLDoc.XML.Text;
end;

//..............................................

//Consuming code example (fragment)
var
  Names,
  Remarks: TStringList;
begin
  //Creating the lists objects
  Names:= TStringList.Create;
  Remarks:= TStringList.Create;
  try
    //Filling the list with names
    Names.Add('April');
    Names.Add('Tam O''Shanter');
    Names.Add('Emily');

    //Filling the list with remarks
    Remarks.Add('Bubbly: I''m > Tam and <= Emily');
    Remarks.Add('Burns: "When chapman billies leave the street ..."');
    Remarks.Add('Short & shrift');

    //Constructing and showing the XML
    Showmessage(CreateXML(Names, Remarks));

  finally
    //Freeing the list objects
    Names.Free;
    Remarks.Free;
  end;
end;


Method traits define: #Y &builder:
  [[| :f | [| :x | f applyWith: (x applyWith: x)]
	   applyWith: [| :x | f applyWith: (x applyWith: x)]]].


Y := [:f| [:x| x value: x] value: [:g| f value: [:x| (g value: g) value: x] ] ].

fib := Y value: [:f| [:i| i <= 1 ifTrue: [i] ifFalse: [(f value: i-1) + (f value: i-2)] ] ].

(fib value: 10) displayNl.

fact := Y value: [:f| [:i| i = 0 ifTrue: [1] ifFalse: [(f value: i-1) * i] ] ].

(fact value: 10) displayNl.


-module( xml_output ).

-export( [task/0] ).

-include_lib("xmerl/include/xmerl.hrl").

task() ->
    Data = {'CharacterRemarks', [], [{'Character', [{name, X}], [[Y]]} || {X, Y} <- contents()]},
    lists:flatten( xmerl:export_simple([Data], xmerl_xml) ).

contents() -> [{"April", "Bubbly: I'm > Tam and <= Emily"}, {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""}, {"Emily", "Short & shrift"}].


function xmlquote(sequence s)
    sequence r
    r = ""
    for i = 1 to length(s) do
        if s[i] = '<' then
            r &= "<"
        elsif s[i] = '>' then
            r &= ">"
        elsif s[i] = '&' then
            r &= "&"
        elsif s[i] = '"' then
            r &= """
        elsif s[i] = '\'' then
            r &= "'"
        else
            r &= s[i]
        end if
    end for
    return r
end function

constant CharacterRemarks = {
    {"April", "Bubbly: I'm > Tam and <= Emily"},
    {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""},
    {"Emily", "Short & shrift"}
}

puts(1,"<CharacterRemarks>\n")
for i = 1 to length(CharacterRemarks) do
    printf(1,"  <CharacterName=\"%s\">",{xmlquote(CharacterRemarks[i][1])})
    puts(1,xmlquote(CharacterRemarks[i][2]))
    puts(1,"</Character>\n")
end for
puts(1,"</CharacterRemarks>\n")


- datatype 'a mu = Roll of ('a mu -> 'a)
  fun unroll (Roll x) = x

  fun fix f = (fn x => fn a => f (unroll x x) a) (Roll (fn x => fn a => f (unroll x x) a))

  fun fac f 0 = 1
    | fac f n = n * f (n-1)

  fun fib f 0 = 0
    | fib f 1 = 1
    | fib f n = f (n-1) + f (n-2)
;
datatype 'a mu = Roll of 'a mu -> 'a
val unroll = fn : 'a mu -> 'a mu -> 'a
val fix = fn : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
val fac = fn : (int -> int) -> int -> int
val fib = fn : (int -> int) -> int -> int
- List.tabulate (10, fix fac);
val it = [1,1,2,6,24,120,720,5040,40320,362880] : int list
- List.tabulate (10, fix fib);
val it = [0,1,1,2,3,5,8,13,21,34] : int list


struct RecursiveFunc<F> {
  let o : RecursiveFunc<F> -> F
}

func Y<A, B>(f: (A -> B) -> A -> B) -> A -> B {
  let r = RecursiveFunc<A -> B> { w in f { w.o(w)($0) } }
  return r.o(r)
}

let fac = Y { (f: Int -> Int) in
  { $0 <= 1 ? 1 : $0 * f($0-1) }
}
let fib = Y { (f: Int -> Int) in
  { $0 <= 2 ? 1 : f($0-1)+f($0-2) }
}
println("fac(5) = \(fac(5))")
println("fib(9) = \(fib(9))")


#light

open System.Xml
type Character = {name : string; comment : string }

let data = [
    { name = "April"; comment = "Bubbly: I'm > Tam and <= Emily"}
    { name = "Tam O'Shanter"; comment = "Burns: \"When chapman billies leave the street ...\""}
    { name = "Emily"; comment = "Short & shrift"} ]

let doxml (characters : Character list) =
    let doc = new XmlDocument()
    let root = doc.CreateElement("CharacterRemarks")
    doc.AppendChild root |> ignore
    Seq.iter (fun who ->
             let node = doc.CreateElement("Character")
             node.SetAttribute("name", who.name)
             doc.CreateTextNode(who.comment)
             |> node.AppendChild |> ignore
             root.AppendChild node |> ignore
             ) characters
    doc.OuterXml


USING: sequences xml.syntax xml.writer ;

: print-character-remarks ( names remarks -- )
    [ [XML <Character name=<-> ><-></Character> XML] ] 2map
    [XML <CharacterRemarks><-></CharacterRemarks> XML] pprint-xml ;


using xml

class XmlOutput
{
  public static Void main ()
  {
    Str[] names := ["April", "Tam O'Shanter", "Emily"]
      Str[] remarks := ["Bubbly: I'm > Tam and <= Emily",
        "Burns: \"When chapman billies leave the street ...\"",
        "Short & shrift"]

    doc := XDoc()
    root := XElem("CharacterRemarks")
    doc.add (root)

    names.each |Str name, Int i|
    {
      child := XElem("Character")
      child.addAttr("Name", name)
      child.add(XText(remarks[i]))
      root.add (child)
    }

    doc.write(Env.cur.out)
  }
}


// YCombinator is not needed since tailspin supports recursion readily, but this demonstrates passing functions as parameters

templates combinator&{stepper:}
  templates makeStep&{rec:}
    $ -> stepper&{next: rec&{rec: rec}} !
  end makeStep
  $ -> makeStep&{rec: makeStep} !
end combinator

templates factorial
  templates seed&{next:}
    <=0> 1 !
    <>
      $ * ($ - 1 -> next) !
  end seed
  $ -> combinator&{stepper: seed} !
end factorial

5 -> factorial -> 'factorial 5: $;
' -> !OUT::write

templates fibonacci
  templates seed&{next:}
    <..1> $ !
    <>
      ($ - 2 -> next) + ($ - 1 -> next) !
  end seed
  $ -> combinator&{stepper: seed} !
end fibonacci

5 -> fibonacci -> 'fibonacci 5: $;
' -> !OUT::write


;; The Y combinator:
(defun y (f)
  [(op @1 @1)
   (op f (op [@@1 @@1]))])

;; The Y-combinator-based factorial:
(defun fac (f)
  (do if (zerop @1)
         1
         (* @1 [f (- @1 1)])))

;; Test:
(format t "~s\n" [[y fac] 4])


include ffl/est.fs
include ffl/xos.fs

\ Input lists
0 value names
here ," Emily"
here ," Tam O'Shanter"
here ," April"
here to names
, , ,

0 value remarks
here ,"  Short & shrift"
here ,\" Burns: \"When chapman billies leave the street ...\""
here ,"  Bubbly: I'm > Tam and <= Emily"
here to remarks
, , ,

: s++ ( c-addr1 -- c-addr2 c-addr3 u3 )
  dup cell+ swap @ count
;

\ Create xml writer
tos-create xml

: create-xml ( c-addr1 c-addr2 -- )
  0 s" CharacterRemarks" xml xos-write-start-tag
  3 0 DO
    swap s++ s" name" 2swap 1
    s" Character" xml xos-write-start-tag
    swap s++      xml xos-write-text
    s" Character" xml xos-write-end-tag
  LOOP
  drop drop
  s" CharacterRemarks" xml xos-write-end-tag
;

names remarks create-xml

\ Output xml string
xml str-get type cr


Data "April", "Bubbly: I'm > Tam and <= Emily", _
    "Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""", _
    "Emily", "Short & shrift"

Declare Function xmlquote(ByRef s As String) As String
Dim n As Integer, dev As String, remark As String

Print "<CharacterRemarks>"
For n = 0 to 2
    Read dev, remark
    Print "  <Character name="""; xmlquote(dev); """>"; _
        xmlquote(remark); "</Character>"
Next
Print "</CharacterRemarks>"

End

Function xmlquote(ByRef s As String) As String
    Dim n As Integer
    Dim r As String
    For n = 0 To Len(s)
        Dim c As String
        c = Mid(s,n,1)
        Select Case As Const Asc(c)
        Case Asc("<")
             r = r + "<"
        Case Asc(">")
             r = r + ">"
        Case Asc("&")
             r = r + "&"
        Case Asc("""")
             r = r + """
        Case Asc("'")
             r = r + "'"
        Case Else
             r = r + c
        End Select
    Next
    Function = r
End Function


package main

import (
    "encoding/xml"
    "fmt"
)

// Function required by task description.
func xRemarks(r CharacterRemarks) (string, error) {
    b, err := xml.MarshalIndent(r, "", "    ")
    return string(b), err
}

// Task description allows the function to take "a single mapping..."
// This data structure represents a mapping.
type CharacterRemarks struct {
    Character []crm
}

type crm struct {
    Name   string `xml:"name,attr"`
    Remark string `xml:",chardata"`
}

func main() {
    x, err := xRemarks(CharacterRemarks{[]crm{
        {`April`, `Bubbly: I'm > Tam and <= Emily`},
        {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`},
        {`Emily`, `Short & shrift`},
    }})
    if err != nil {
        x = err.Error()
    }
    fmt.Println(x)
}


Private Function call_fn(f As String, n As Long) As Long
    call_fn = Application.Run(f, f, n)
End Function

Private Function Y(f As String) As String
    Y = f
End Function

Private Function fac(self As String, n As Long) As Long
    If n > 1 Then
        fac = n * call_fn(self, n - 1)
    Else
        fac = 1
    End If
End Function

Private Function fib(self As String, n As Long) As Long
    If n > 1 Then
        fib = call_fn(self, n - 1) + call_fn(self, n - 2)
    Else
        fib = n
    End If
End Function

Private Sub test(name As String)
    Dim f As String: f = Y(name)
    Dim i As Long
    Debug.Print name
    For i = 1 To 10
        Debug.Print call_fn(f, i);
    Next i
    Debug.Print
End Sub

Public Sub main()
    test "fac"
    test "fib"
End Sub


/////// Y-combinator function (for single-argument lambdas) ///////

y @FN [f]
{ @( x -> { @f (z -> {@(@x x) z}) } )   // output of this expression is treated as a verb, due to outer @(  )
   ( x -> { @f (z -> {@(@x x) z}) } )   // this is the argument supplied to the above verb expression
};

/////// Function to generate an anonymous factorial function as the return value -- (not tail-recursive) ///////

fact_gen @FN [f]
{ n -> { (n<=0) ? {1} {n * (@f n-1)}
       }
};

/////// Function to generate an anonymous fibonacci function as the return value -- (not tail-recursive) ///////

fib_gen @FN [f]
{ n -> { (n<=0) ? { 0                                    }
                  { (n<=2) ? {1} { (@f n-1) + (@f n-2) } }
       }
};

/////// loops to test the above functions ///////

@VAR factorial = @y fact_gen;
@VAR fibonacci = @y fib_gen;

@LOOP init:{@VAR i = -1} while:(i <= 20) next:{i++}
{ @SAY  i "factorial =" (@factorial i) };

@LOOP init:{     i = -1} while:(i <= 16) next:{i++}
{ @SAY "fibonacci<" i "> =" (@fibonacci i) };


def writer = new StringWriter()
def builder = new groovy.xml.MarkupBuilder(writer)
def names = ["April", "Tam O'Shanter", "Emily"]
def remarks = ["Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift"]

builder.CharacterRemarks() {
    names.eachWithIndex() { n, i -> Character(name:n, remarks[i]) };
}

println writer.toString()


import Text.XML.Light

characterRemarks :: [String] -> [String] -> String
characterRemarks names remarks = showElement $ Element
    (unqual "CharacterRemarks")
    []
    (zipWith character names remarks)
    Nothing
  where character name remark = Elem $ Element
            (unqual "Character")
            [Attr (unqual "name") name]
            [Text $ CData CDataText remark Nothing]
            Nothing


CHARACTER names="April~Tam O'Shanter~Emily~"
CHARACTER remarks*200/%Bubbly: I'm > Tam and <= Emily~Burns: "When chapman billies leave the street ..."~Short & shrift~%/
CHARACTER XML*1000

EDIT(Text=remarks, Right='&', RePLaceby='&', DO)
EDIT(Text=remarks, Right='>', RePLaceby='>', DO)
EDIT(Text=remarks, Right='<', RePLaceby='<', DO)

XML = "<CharacterRemarks>" // $CRLF
DO i = 1, 3
  EDIT(Text=names, SePaRators='~', ITeM=i, Parse=name)
  EDIT(Text=remarks, SePaRators='~', ITeM=i, Parse=remark)
  XML = TRIM(XML) // '<Character name="' // name // '">' // remark // '</Character>' // $CRLF
ENDDO
XML = TRIM(XML) // "</CharacterRemarks>"


" Translated from Python.  Works with: Vim 7.0

func! Lambx(sig, expr, dict)
    let fanon = {'d': a:dict}
    exec printf("
	\func fanon.f(%s) dict\n
	\  return %s\n
	\endfunc",
	\ a:sig, a:expr)
    return fanon
endfunc

func! Callx(fanon, arglist)
    return call(a:fanon.f, a:arglist, a:fanon.d)
endfunc

let g:Y = Lambx('f', 'Callx(Lambx("x", "Callx(a:x, [a:x])", {}), [Lambx("y", ''Callx(self.f, [Lambx("...", "Callx(Callx(self.y, [self.y]), a:000)", {"y": a:y})])'', {"f": a:f})])', {})

let g:fac = Lambx('f', 'Lambx("n", "a:n<2 ? 1 : a:n * Callx(self.f, [a:n-1])", {"f": a:f})', {})

echo Callx(Callx(g:Y, [g:fac]), [5])
echo map(range(10), 'Callx(Callx(Y, [fac]), [v:val])')


# Better names due to Jim Weirich: http://vimeo.com/45140590
def (Y improver)
  ((fn(gen) gen.gen)
   (fn(gen)
     (fn(n)
       ((improver gen.gen) n))))

factorial <- (Y (fn(f)
                  (fn(n)
                    (if zero?.n
                      1
                      (n * (f n-1))))))

prn factorial.5


import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlCreation {

  private static final String[] names = {"April", "Tam O'Shanter", "Emily"};
  private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily",
    "Burns: \"When chapman billies leave the street ...\"",
      "Short & shrift"};

  public static void main(String[] args) {
    try {
      // Create a new XML document
      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

      // Append the root element
      final Element root = doc.createElement("CharacterRemarks");
      doc.appendChild(root);

      // Read input data and create a new <Character> element for each name.
      for(int i = 0; i < names.length; i++) {
        final Element character = doc.createElement("Character");
        root.appendChild(character);
        character.setAttribute("name", names[i]);
        character.appendChild(doc.createTextNode(remarks[i]));
      }

      // Serializing XML in Java is unnecessary complicated
      // Create a Source from the document.
      final Source source = new DOMSource(doc);

      // This StringWriter acts as a buffer
      final StringWriter buffer = new StringWriter();

      // Create a Result as a transformer target.
      final Result result = new StreamResult(buffer);

      // The Transformer is used to copy the Source to the Result object.
      final Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty("indent", "yes");
      transformer.transform(source, result);

      // Now the buffer is filled with the serialized XML and we can print it
      // to the console.
      System.out.println(buffer.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}


var y = Fn.new { |f|
    var g = Fn.new { |r| f.call { |x| r.call(r).call(x) } }
    return g.call(g)
}

var almostFac = Fn.new { |f| Fn.new { |x| x <= 1 ? 1 : x * f.call(x-1) } }

var almostFib = Fn.new { |f| Fn.new { |x| x <= 2 ? 1 : f.call(x-1) + f.call(x-2) } }

var fac = y.call(almostFac)
var fib = y.call(almostFib)

System.print("fac(10) = %(fac.call(10))")
System.print("fib(10) = %(fib.call(10))")


let $Y := function($f) {
    (function($x) { ($x)($x) })( function($g) { $f( (function($a) { $g($g) ($a)})  ) } )
  }
let $fac := $Y(function($f) { function($n) { if($n <  2) then 1  else $n * $f($n - 1) } })
let $fib := $Y(function($f) { function($n) { if($n <= 1) then $n else $f($n - 1) + $f($n - 2) } })
return (
    $fac(6),
    $fib(6)
)


DEFINE subst ==
[[['< "<"  putchars]
  ['> ">"  putchars]
  ['& "&" putchars]
  [putch]] case] step;

XMLOutput ==
"<CharacterRemarks>\n" putchars
[ "<Character name=\"" putchars uncons swap putchars "\">" putchars first subst  "</Character>\n" putchars] step
"</CharacterRemarks>\n" putchars.

[ [ "April" "Bubbly: I'm > Tam and <= Emily" ]
  [ "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\"" ]
  [ "Emily" "Short & shrift" ]
] XMLOutput.


using LightXML

dialog = [("April", "Bubbly: I'm > Tam and <= Emily"),
          ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""),
          ("Emily", "Short & shrift")]

const xdoc = XMLDocument()
const xroot = create_root(xdoc, "CharacterRemarks")

for (name, remarks) in dialog
    xs1 = new_child(xroot, "Character")
    set_attribute(xs1, "name", name)
    add_text(xs1, remarks)
end

println(xdoc)


// version 1.1.3

import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.dom.DOMSource
import java.io.StringWriter
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.TransformerFactory

fun main(args: Array<String>) {
    val names = listOf("April", "Tam O'Shanter", "Emily")

    val remarks = listOf(
        "Bubbly: I'm > Tam and <= Emily",
        "Burns: \"When chapman billies leave the street ...\"",
        "Short & shrift"
    )

    val dbFactory = DocumentBuilderFactory.newInstance()
    val dBuilder  = dbFactory.newDocumentBuilder()
    val doc = dBuilder.newDocument()
    val root = doc.createElement("CharacterRemarks") // create root node
    doc.appendChild(root)

    // now create Character elements
    for (i in 0 until names.size) {
        val character = doc.createElement("Character")
        character.setAttribute("name", names[i])
        val remark = doc.createTextNode(remarks[i])
        character.appendChild(remark)
        root.appendChild(character)
    }

    val source = DOMSource(doc)
    val sw = StringWriter()
    val result = StreamResult(sw)
    val tFactory = TransformerFactory.newInstance()
    tFactory.newTransformer().apply {
        setOutputProperty("omit-xml-declaration", "yes")
        setOutputProperty("indent", "yes")
        setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
        transform(source, result)
    }
    println(sw)
}


sub fac(self$, n)
    if n > 1 then
        return n * execute(self$, self$, n - 1)
    else
        return 1
    end if
end sub

sub fib(self$, n)
    if n > 1 then
        return execute(self$, self$, n - 1) + execute(self$, self$, n - 2)
    else
        return n
    end if
end sub

sub test(name$)
    local i

    print name$, ": ";
    for i = 1 to 10
        print execute(name$, name$, i);
    next
    print
end sub

test("fac")
test("fib")


define character2xml(names::array, remarks::array) => {

	fail_if(#names -> size != #remarks -> size, -1, 'Input arrays not of same size')

	local(
		domimpl = xml_domimplementation,
		doctype = #domimpl -> createdocumenttype(
			'svg:svg',
			'-//W3C//DTD SVG 1.1//EN',
			'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'
		),
		character_xml = #domimpl -> createdocument(
			'http://www.w3.org/2000/svg',
			'svg:svg',
			#docType
		),
		csnode = #character_xml -> createelement('CharacterRemarks'),
		charnode
	)

	#character_xml -> appendChild(#csnode)

	loop(#names -> size) => {
		#charnode = #character_xml -> createelement('Character')
		#charnode -> setAttribute('name', #names  -> get(loop_count))
		#charnode -> nodeValue = encode_xml(#remarks -> get(loop_count))
		#csnode -> appendChild(#charnode)
	}
	return #character_xml

}

character2xml(
	array(`April`, `Tam O'Shanter`, `Emily`),
	array(`Bubbly: I'm > Tam and <= Emily`, `Burns: "When chapman billies leave the street ..."`, `Short & shrift`)
)


require("LuaXML")

function addNode(parent, nodeName, key, value, content)
    local node = xml.new(nodeName)
    table.insert(node, content)
    parent:append(node)[key] = value
end

root = xml.new("CharacterRemarks")
addNode(root, "Character", "name", "April", "Bubbly: I'm > Tam and <= Emily")
addNode(root, "Character", "name", "Tam O'Shanter", 'Burns: "When chapman billies leave the street ..."')
addNode(root, "Character", "name", "Emily", "Short & shrift")
print(root)


c = {"April", "Tam O'Shanter","Emily"};
r = {"Bubbly:I'm > Tam and <= Emily" ,
StringReplace["Burns:\"When chapman billies leave the street ...\"", "\"" -> ""], "Short & shrift"};
ExportString[ XMLElement[  "CharacterRemarks", {},
{XMLElement["Character", {"name" -> c[[1]]}, {r[[1]]}],
 XMLElement["Character", {"name" -> c[[2]]}, {r[[2]]}],
 XMLElement["Character", {"name" -> c[[3]]}, {r[[3]]}]
}], "XML", "AttributeQuoting" -> "\""]


RootXML = com.mathworks.xml.XMLUtils.createDocument('CharacterRemarks');
docRootNode = RootXML.getDocumentElement;
thisElement = RootXML.createElement('Character');
thisElement.setAttribute('Name','April')
thisElement.setTextContent('Bubbly: I''m > Tam and <= Emily');
docRootNode.appendChild(thisElement);
thisElement = RootXML.createElement('Character');
thisElement.setAttribute('Name','Tam O''Shanter')
thisElement.setTextContent('Burns: "When chapman billies leave the street ..."');
docRootNode.appendChild(thisElement);
thisElement = RootXML.createElement('Character');
thisElement.setAttribute('Name','Emily')
thisElement.setTextContent('Short & shrift');
docRootNode.appendChild(thisElement);


/* NetRexx */

options replace format comments java crossref savelog symbols nobinary

import java.io.StringWriter

import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.Result
import javax.xml.transform.Source
import javax.xml.transform.Transformer
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult

import org.w3c.dom.Document
import org.w3c.dom.Element

names = [String -
  "April", "Tam O'Shanter", "Emily" -
]

remarks = [ String -
     "Bubbly: I'm > Tam and <= Emily" -
  ,  'Burns: "When chapman billies leave the street ..."' -
  ,  'Short & shrift' -
]

do
  -- Create a new XML document
  doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()

  -- Append the root element
  root = doc.createElement("CharacterRemarks")
  doc.appendChild(root)

  -- Read input data and create a new <Character> element for each name.
  loop i_ = 0 to names.length - 1
    character = doc.createElement("Character")
    root.appendChild(character)
    character.setAttribute("name", names[i_])
    character.appendChild(doc.createTextNode(remarks[i_]))
    end i_

  -- Serializing XML in Java is unnecessary complicated
  -- Create a Source from the document.
  source = DOMSource(doc)

  -- This StringWriter acts as a buffer
  buffer = StringWriter()

  -- Create a Result as a transformer target.
  result = StreamResult(buffer)

  -- The Transformer is used to copy the Source to the Result object.
  transformer = TransformerFactory.newInstance().newTransformer()
  transformer.setOutputProperty("indent", "yes")
  transformer.transform(source, result)

  -- Now the buffer is filled with the serialized XML and we can print it to the console.
  say buffer.toString
catch ex = Exception
  ex.printStackTrace
end

return


import xmltree, strtabs, sequtils

proc charsToXML(names, remarks: seq[string]): XmlNode =
  result = <>CharacterRemarks()
  for name, remark in items zip(names, remarks):
    result.add <>Character(name=name, remark.newText)

echo charsToXML(@["April", "Tam O'Shanter", "Emily"],
  @["Bubbly: I'm > Tam and <= Emily",
    "Burns: \"When chapman billies leave the street ...\"",
    "Short & shrift"])


use Data.XML;
use Collection.Generic;

class Test {
  function : Main(args : String[]) ~ Nil {
    # list of name
    names := Vector->New()<String>;
    names->AddBack("April");
    names->AddBack("Tam O'Shanter");
    names->AddBack("Emily");
    # list of comments
    comments := Vector->New()<String>;
    comments->AddBack("Bubbly: I'm > Tam and <= Emily");
    comments->AddBack("Burns: \"When chapman billies leave the street ...\"");
    comments->AddBack(XmlElement->EncodeString("Short & shrift");
    # build XML document
    builder := XmlBuilder->New("CharacterRemarks");
    root := builder->GetRoot();
    if(names->Size() = comments->Size()) {
      each(i : names) {
        element := XmlElement->New(XmlElement->Type->ELEMENT, "Character");
        element->AddAttribute(XmlAttribute->New("name", names->Get(i)));
        element->SetContent(XmlElement->EncodeString(comments->Get(i)));
        root->AddChild(element);
      };
    };
    builder->ToString()->PrintLine();
  }
}


# #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;;

# #load "xml-light.cma" ;;

# let data = [
    ("April", "Bubbly: I'm > Tam and <= Emily");
    ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"");
    ("Emily", "Short & shrift");
  ] in
  let tags =
    List.map (fun (name, comment) ->
      Xml.Element ("Character", [("name", name)], [(Xml.PCData comment)])
    ) data
  in
  print_endline (
    Xml.to_string_fmt (Xml.Element ("CharacterRemarks", [], tags)))
  ;;
<CharacterRemarks>
  <Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
  <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
  <Character name="Emily">Short & shrift</Character>
</CharacterRemarks>
- : unit = ()


declare
  proc {Main}
     Names = ["April"
	      "Tam O'Shanter"
	      "Emily"]

     Remarks = ["Bubbly: I'm > Tam and <= Emily"
		"Burns: \"When chapman billies leave the street ...\""
		"Short & shrift"]

     Characters = {List.zip Names Remarks
		   fun {$ N R}
		      'Character'(name:N R)
		   end}

     DOM = {List.toTuple 'CharacterRemarks' Characters}
  in
     {System.showInfo {Serialize DOM}}
  end

  fun {Serialize DOM}
     "<?xml version=\"1.0\" ?>\n"#
     {SerializeElement DOM 0}
  end

  fun {SerializeElement El Indent}
     Name = {Label El}
     Attributes ChildElements Contents
     {DestructureElement El ?Attributes ?ChildElements ?Contents}
     EscContents = {Map Contents Escape}
     Spaces = {List.make Indent} for S in Spaces do S = &  end
  in
     Spaces#"<"#Name#
     {VSConcatMap Attributes SerializeAttribute}#">"#
     {VSConcat EscContents}#{When ChildElements\=nil "\n"}#
     {VSConcatMap ChildElements fun {$ E} {SerializeElement E Indent+4} end}#
     {When ChildElements\=nil Spaces}#"</"#Name#">\n"
  end

  proc {DestructureElement El ?Attrs ?ChildElements ?Contents}
     SubelementRec AttributeRec
     {Record.partitionInd El fun {$ I _} {Int.is I} end
      ?SubelementRec ?AttributeRec}
     Subelements = {Record.toList SubelementRec}
  in
     {List.partition Subelements VirtualString.is ?Contents ?ChildElements}
     Attrs = {Record.toListInd AttributeRec}
  end

  fun {SerializeAttribute Name#Value}
     " "#Name#"=\""#{EscapeAttribute Value}#"\""
  end

  fun {Escape VS}
     {Flatten {Map {VirtualString.toString VS} EscapeChar}}
  end

  fun {EscapeAttribute VS}
     {Flatten {Map {VirtualString.toString VS} EscapeAttributeChar}}
  end

  fun {EscapeChar X}
     case X of 60 then "<"
     [] 62 then ">"
     [] 38 then "&"
     else X
     end
  end

  fun {EscapeAttributeChar X}
     case X of 34 then """
     else {EscapeChar X}
     end
  end

  %% concatenates a list to a virtual string
  fun {VSConcat Xs}
     {List.toTuple '#' Xs}
  end

  fun {VSConcatMap Xs F}
     {VSConcat {Map Xs F}}
  end

  fun {When Cond X}
     if Cond then X else nil end
  end
in
  {Main}


#! /usr/bin/perl
use strict;
use XML::Mini::Document;

my @students = ( [ "April", "Bubbly: I'm > Tam and <= Emily" ],
                 [ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" ],
		 [ "Emily", "Short & shrift" ]
                );

my $doc = XML::Mini::Document->new();
my $root = $doc->getRoot();
my $studs = $root->createChild("CharacterRemarks");
foreach my $s (@students)
{
    my $stud = $studs->createChild("Character");
    $stud->attribute("name", $s->[0]);
    $stud->text($s->[1]);
}
print $doc->toString();


with javascript_semantics
constant {hchars,hsubs} = columnize({{"<","<"},
                                     {">",">"},
                                     {"&","&"},
                                     {"\"","""},
                                     {"\'","'"}})
function xmlquote_all(sequence s)
    for i=1 to length(s) do
        s[i] = substitute_all(s[i],hchars,hsubs)
    end for
    return s
end function

function xml_CharacterRemarks(sequence data)
string res = "<CharacterRemarks>\n"
    for i=1 to length(data) do
        res &= sprintf("  <CharacterName=\"%s\">%s</Character>\n",xmlquote_all(data[i]))
    end for
    return res & "</CharacterRemarks>\n"
end function

constant testset = {
    {"April", "Bubbly: I'm > Tam and <= Emily"},
    {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""},
    {"Emily", "Short & shrift"}
}
printf(1,xml_CharacterRemarks(testset))

-- Sample output:
--  <CharacterRemarks>
--    <CharacterName="April">Bubbly: I'm > Tam and <= Emily</Character>
--    <CharacterName="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
--    <CharacterName="Emily">Short & shrift</Character>
--  </CharacterRemarks>


(load "@lib/xml.l")

(de characterRemarks (Names Remarks)
   (xml
      (cons
         'CharacterRemarks
         NIL
         (mapcar
            '((Name Remark)
               (list 'Character (list (cons 'name Name)) Remark) )
            Names
            Remarks ) ) ) )

(characterRemarks
   '("April" "Tam O'Shanter" "Emily")
   (quote
      "I'm > Tam and <= Emily"
      "Burns: \"When chapman billies leave the street ..."
      "Short & shrift" ) )


DataSection
  dataItemCount:
  Data.i 3

  names:
  Data.s "April", "Tam O'Shanter", "Emily"

  remarks:
  Data.s "Bubbly: I'm > Tam and <= Emily",
         ~"Burns: \"When chapman billies leave the street ...\"",
         "Short & shrift"
EndDataSection

Structure characteristic
  name.s
  remark.s
EndStructure

NewList didel.characteristic()
Define item.s, numberOfItems, i

Restore dataItemCount
Read.i numberOfItems

;add names
Restore names
For i = 1 To numberOfItems
  AddElement(didel())
  Read.s item
  didel()\name = item
Next

;add remarks
ResetList(didel())
FirstElement(didel())
Restore remarks:
For i = 1 To numberOfItems
  Read.s item
  didel()\remark = item
  NextElement(didel())
Next

Define xml, mainNode, itemNode
ResetList(didel())
FirstElement(didel())
xml = CreateXML(#PB_Any)
mainNode = CreateXMLNode(RootXMLNode(xml), "CharacterRemarks")
ForEach didel()
  itemNode = CreateXMLNode(mainNode, "Character")
  SetXMLAttribute(itemNode, "name", didel()\name)
  SetXMLNodeText(itemNode, didel()\remark)
Next
FormatXML(xml, #PB_XML_ReFormat |  #PB_XML_WindowsNewline | #PB_XML_ReIndent)

If OpenConsole()
  PrintN(ComposeXML(xml, #PB_XML_NoDeclaration))
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


>>> from xml.etree import ElementTree as ET
>>> from itertools import izip
>>> def characterstoxml(names, remarks):
	root = ET.Element("CharacterRemarks")
	for name, remark in izip(names, remarks):
		c = ET.SubElement(root, "Character", {'name': name})
		c.text = remark
	return ET.tostring(root)

>>> print characterstoxml(
	names = ["April", "Tam O'Shanter", "Emily"],
	remarks = [ "Bubbly: I'm > Tam and <= Emily",
		    'Burns: "When chapman billies leave the street ..."',
		    'Short & shrift' ] ).replace('><','>\n<')


library(XML)
char2xml <- function(names, remarks){
	tt <- xmlHashTree()
	head <- addNode(xmlNode("CharacterRemarks"), character(), tt)
	node <- list()
	for (i in 1:length(names)){
		node[[i]] <- addNode(xmlNode("Character", attrs=c(name=names[i])), head, tt)
		addNode(xmlTextNode(remarks[i]), node[[i]], tt)
	}
	return(tt)
}
output <- char2xml( names=c("April","Tam O'Shanter","Emily"),
remarks=c("Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift") )


#lang racket
(require xml)

(define (make-character-xexpr characters remarks)
  `(CharacterRemarks
    ,@(for/list ([character characters]
                [remark remarks])
       `(Character ((name ,character)) ,remark))))

(display-xml/content
 (xexpr->xml
  (make-character-xexpr
   '("April" "Tam O'Shanter" "Emily")
   '("Bubbly: I'm > Tam and <= Emily"
     "Burns: \"When chapman billies leave the street ...\""
     "Short & shrift"))))


use XML::Writer;

my @students =
    [ Q[April],         Q[Bubbly: I'm > Tam and <= Emily] ],
    [ Q[Tam O'Shanter], Q[Burns: "When chapman billies leave the street ..."] ],
    [ Q[Emily],         Q[Short & shrift] ]
;

my @lines = map { :Character[:name(.[0]), .[1]] }, @students;

say XML::Writer.serialize( CharacterRemarks => @lines );


import Prelude;
import lang::xml::DOM;

list[str] charnames = ["April", "Tam O\'Shanter", "Emily"];
list[str] remarks = ["Bubbly: I\'m \> Tam and \<= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"];

public void xmloutput(list[str] n,list[str] r){
	if(size(n) != size(r)){
		throw "n and r should be of the same size";
                }
	else{
		characters = [element(none(),"Character",[attribute(none(),"name",n[i]), charData(r[i])]),charData("\n")| i <- [0..size(n)-1]];
		x = document(element(none(),"CharacterRemarks",characters));
		return println(xmlPretty(x));
                }
}


/*REXX program creates an HTML (XML) list of character names and corresponding remarks. */
charname.  =
charname.1 = "April"
charname.2 = "Tam O'Shanter"
charname.3 = "Emily"
                                     do i=1  while  charname.i\==''
                                     say 'charname'   i   '='   charname.i
                                     end   /*i*/;     say
remark.  =
remark.1 = "I'm > Tam and <= Emily"
remark.2 = "When chapman billies leave the street ..."
remark.3 = "Short & shift"
                                     do k=1  while  remark.k\==''
                                     say '  remark'   k   '='   remark.k
                                     end   /*k*/;     say
items  = 0
header = 'CharacterRemarks'
header = header'>'

    do j=1  while  charname.j\==''
    _=charname.j
    if j==1  then call create '<'header
    call create '    <Character name="'  ||,
                char2xml(_)'">"'         ||,
                char2xml(remark.j)'"</Character>'
    end   /*j*/

if create.0\==0  then call create '</'header

        do m=1  for create.0
        say create.m                             /*display the  Mth  entry to terminal. */
        end   /*m*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
char2xml: procedure;  parse arg $
          amper = pos('&', $)\==0                /*  &   has to be treated special.     */
          semi  = pos(';', $)\==0                /*  ;    "   "  "    "       "         */
          #=0                                    /* [↓]  find a free/unused character···*/
          if amper  then do                      /*          ··· and translate freely.  */
                           do j=0  for 255;    ?=d2c(j);    if pos(?, $)==0   then leave
                           end   /*j*/
                         $=translate($, ?, "&");            #= j + 1
                         end
                                                 /* [↓]  find a free/unused character···*/
          if semi   then do                      /*          ··· and translate freely.  */
                           do k=#  for 255;    ?=d2c(k);    if pos(?, $)==0  then leave
                           end   /*k*/
                         $=translate($, ?, ";")
                         end

/*───── Following are most of the characters in the  DOS  (or DOS Windows)  codepage  437 ──────────*/

$=XML_('â',"ETH")    ; $=XML_('ƒ',"fnof")  ; $=XML_('═',"boxH")      ; $=XML_('♥',"hearts")
$=XML_('â','#x00e2') ; $=XML_('á',"aacute"); $=XML_('╬',"boxVH")     ; $=XML_('♦',"diams")
$=XML_('â','#x00e9') ; $=XML_('á','#x00e1'); $=XML_('╧',"boxHu")     ; $=XML_('♣',"clubs")
$=XML_('ä',"auml")   ; $=XML_('í',"iacute"); $=XML_('╨',"boxhU")     ; $=XML_('♠',"spades")
$=XML_('ä','#x00e4') ; $=XML_('í','#x00ed'); $=XML_('╤',"boxHd")     ; $=XML_('♂',"male")
$=XML_('à',"agrave") ; $=XML_('ó',"oacute"); $=XML_('╥',"boxhD")     ; $=XML_('♀',"female")
$=XML_('à','#x00e0') ; $=XML_('ó','#x00f3'); $=XML_('╙',"boxUr")     ; $=XML_('☼',"#x263c")
$=XML_('å',"aring")  ; $=XML_('ú',"uacute"); $=XML_('╘',"boxuR")     ; $=XML_('↕',"UpDownArrow")
$=XML_('å','#x00e5') ; $=XML_('ú','#x00fa'); $=XML_('╒',"boxdR")     ; $=XML_('¶',"para")
$=XML_('ç',"ccedil") ; $=XML_('ñ',"ntilde"); $=XML_('╓',"boxDr")     ; $=XML_('§',"sect")
$=XML_('ç','#x00e7') ; $=XML_('ñ','#x00f1'); $=XML_('╫',"boxVh")     ; $=XML_('↑',"uarr")
$=XML_('ê',"ecirc")  ; $=XML_('Ñ',"Ntilde"); $=XML_('╪',"boxvH")     ; $=XML_('↑',"uparrow")
$=XML_('ê','#x00ea') ; $=XML_('Ñ','#x00d1'); $=XML_('┘',"boxul")     ; $=XML_('↑',"ShortUpArrow")
$=XML_('ë',"euml")   ; $=XML_('¿',"iquest"); $=XML_('┌',"boxdr")     ; $=XML_('↓',"darr")
$=XML_('ë','#x00eb') ; $=XML_('⌐',"bnot")  ; $=XML_('█',"block")     ; $=XML_('↓',"downarrow")
$=XML_('è',"egrave") ; $=XML_('¬',"not")   ; $=XML_('▄',"lhblk")     ; $=XML_('↓',"ShortDownArrow")
$=XML_('è','#x00e8') ; $=XML_('½',"frac12"); $=XML_('▀',"uhblk")     ; $=XML_('←',"larr")
$=XML_('ï',"iuml")   ; $=XML_('½',"half")  ; $=XML_('α',"alpha")     ; $=XML_('←',"leftarrow")
$=XML_('ï','#x00ef') ; $=XML_('¼',"frac14"); $=XML_('ß',"beta")      ; $=XML_('←',"ShortLeftArrow")
$=XML_('î',"icirc")  ; $=XML_('¡',"iexcl") ; $=XML_('ß',"szlig")     ; $=XML_('1c'x,"rarr")
$=XML_('î','#x00ee') ; $=XML_('«',"laqru") ; $=XML_('ß','#x00df')    ; $=XML_('1c'x,"rightarrow")
$=XML_('ì',"igrave") ; $=XML_('»',"raqru") ; $=XML_('Γ',"Gamma")     ; $=XML_('1c'x,"ShortRightArrow")
$=XML_('ì','#x00ec') ; $=XML_('░',"blk12") ; $=XML_('π',"pi")        ; $=XML_('!',"excl")
$=XML_('Ä',"Auml")   ; $=XML_('▒',"blk14") ; $=XML_('Σ',"Sigma")     ; $=XML_('"',"apos")
$=XML_('Ä','#x00c4') ; $=XML_('▓',"blk34") ; $=XML_('σ',"sigma")     ; $=XML_('$',"dollar")
$=XML_('Å',"Aring")  ; $=XML_('│',"boxv")  ; $=XML_('µ',"mu")        ; $=XML_("'","quot")
$=XML_('Å','#x00c5') ; $=XML_('┤',"boxvl") ; $=XML_('τ',"tau")       ; $=XML_('*',"ast")
$=XML_('É',"Eacute") ; $=XML_('╡',"boxvL") ; $=XML_('Φ',"phi")       ; $=XML_('/',"sol")
$=XML_('É','#x00c9') ; $=XML_('╢',"boxVl") ; $=XML_('Θ',"Theta")     ; $=XML_(':',"colon")
$=XML_('æ',"aelig")  ; $=XML_('╖',"boxDl") ; $=XML_('δ',"delta")     ; $=XML_('<',"lt")
$=XML_('æ','#x00e6') ; $=XML_('╕',"boxdL") ; $=XML_('∞',"infin")     ; $=XML_('=',"equals")
$=XML_('Æ',"AElig")  ; $=XML_('╣',"boxVL") ; $=XML_('φ',"Phi")       ; $=XML_('>',"gt")
$=XML_('Æ','#x00c6') ; $=XML_('║',"boxV")  ; $=XML_('ε',"epsilon")   ; $=XML_('?',"quest")
$=XML_('ô',"ocirc")  ; $=XML_('╗',"boxDL") ; $=XML_('∩',"cap")       ; $=XML_('_',"commat")
$=XML_('ô','#x00f4') ; $=XML_('╝',"boxUL") ; $=XML_('≡',"equiv")     ; $=XML_('[',"lbrack")
$=XML_('ö',"ouml")   ; $=XML_('╜',"boxUl") ; $=XML_('±',"plusmn")    ; $=XML_('\',"bsol")
$=XML_('ö','#x00f6') ; $=XML_('╛',"boxuL") ; $=XML_('±',"pm")        ; $=XML_(']',"rbrack")
$=XML_('ò',"ograve") ; $=XML_('┐',"boxdl") ; $=XML_('±',"PlusMinus") ; $=XML_('^',"Hat")
$=XML_('ò','#x00f2') ; $=XML_('└',"boxur") ; $=XML_('≥',"ge")        ; $=XML_('`',"grave")
$=XML_('û',"ucirc")  ; $=XML_('┴',"bottom"); $=XML_('≤',"le")        ; $=XML_('{',"lbrace")
$=XML_('û','#x00fb') ; $=XML_('┴',"boxhu") ; $=XML_('÷',"div")       ; $=XML_('{',"lcub")
$=XML_('ù',"ugrave") ; $=XML_('┬',"boxhd") ; $=XML_('÷',"divide")    ; $=XML_('|',"vert")
$=XML_('ù','#x00f9') ; $=XML_('├',"boxvr") ; $=XML_('≈',"approx")    ; $=XML_('|',"verbar")
$=XML_('ÿ',"yuml")   ; $=XML_('─',"boxh")  ; $=XML_('∙',"bull")      ; $=XML_('}',"rbrace")
$=XML_('ÿ','#x00ff') ; $=XML_('┼',"boxvh") ; $=XML_('°',"deg")       ; $=XML_('}',"rcub")
$=XML_('Ö',"Ouml")   ; $=XML_('╞',"boxvR") ; $=XML_('·',"middot")    ; $=XML_('Ç',"Ccedil")
$=XML_('Ö','#x00d6') ; $=XML_('╟',"boxVr") ; $=XML_('·',"middledot") ; $=XML_('Ç','#x00c7')
$=XML_('Ü',"Uuml")   ; $=XML_('╚',"boxUR") ; $=XML_('·',"centerdot") ; $=XML_('ü',"uuml")
$=XML_('Ü','#x00dc') ; $=XML_('╔',"boxDR") ; $=XML_('·',"CenterDot") ; $=XML_('ü','#x00fc')
$=XML_('¢',"cent")   ; $=XML_('╩',"boxHU") ; $=XML_('√',"radic")     ; $=XML_('é',"eacute")
$=XML_('£',"pound")  ; $=XML_('╦',"boxHD") ; $=XML_('²',"sup2")      ; $=XML_('é','#x00e9')
$=XML_('¥',"yen")    ; $=XML_('╠',"boxVR") ; $=XML_('■',"square ")   ; $=XML_('â',"acirc")

          if amper  then $=xml_(?,  "amp")       /*Was there an ampersand?  Translate it*/
          if semi   then $=xml_(??, "semi")      /* "   "     " semicolon?      "      "*/
          return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
create:          items= items + 1                /*bump the count of items in the list. */
          create.items= arg(1)                   /*add item to the  CREATE  list.       */
          create.0    = items                    /*indicate how many items in the list. */
          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
xml_:     parse arg _                            /*make an XML entity    (&xxxx;)       */
          if pos(_, $)\==0  then return changestr(_, $, "&"arg(2)";")
                                 return $


require 'rexml/document'
include REXML

remarks = {
  %q(April)         => %q(Bubbly: I'm > Tam and <= Emily),
  %q(Tam O'Shanter) => %q(Burns: "When chapman billies leave the street ..."),
  %q(Emily)         => %q(Short & shrift),
}

doc = Document.new
root = doc.add_element("CharacterRemarks")

remarks.each do |name, remark|
  root.add_element("Character", {'Name' => name}).add_text(remark)
end

# output with indentation
doc.write($stdout, 2)


extern crate xml;

use std::collections::HashMap;
use std::str;

use xml::writer::{EmitterConfig, XmlEvent};

fn characters_to_xml(characters: HashMap<String, String>) -> String {
    let mut output: Vec<u8> = Vec::new();
    let mut writer = EmitterConfig::new()
        .perform_indent(true)
        .create_writer(&mut output);

    writer
        .write(XmlEvent::start_element("CharacterRemarks"))
        .unwrap();

    for (character, line) in &characters {
        let element = XmlEvent::start_element("Character").attr("name", character);
        writer.write(element).unwrap();
        writer.write(XmlEvent::characters(line)).unwrap();
        writer.write(XmlEvent::end_element()).unwrap();
    }

    writer.write(XmlEvent::end_element()).unwrap();
    str::from_utf8(&output).unwrap().to_string()
}

#[cfg(test)]
mod tests {
    use super::characters_to_xml;
    use std::collections::HashMap;

    #[test]
    fn test_xml_output() {
        let mut input = HashMap::new();
        input.insert(
            "April".to_string(),
            "Bubbly: I'm > Tam and <= Emily".to_string(),
        );
        input.insert(
            "Tam O'Shanter".to_string(),
            "Burns: \"When chapman billies leave the street ...\"".to_string(),
        );
        input.insert("Emily".to_string(), "Short & shrift".to_string());

        let output = characters_to_xml(input);

        println!("{}", output);
        assert!(output.contains(
            "<Character name=\"Tam O'Shanter\">Burns: \"When chapman \
             billies leave the street ...\"</Character>"
        ));
        assert!(output
            .contains("<Character name=\"April\">Bubbly: I'm > Tam and <= Emily</Character>"));
        assert!(output.contains("<Character name=\"Emily\">Short & shrift</Character>"));
    }
}


val names = List("April", "Tam O'Shanter", "Emily")

val remarks = List("Bubbly: I'm > Tam and <= Emily", """Burns: "When chapman billies leave the street ..."""", "Short & shrift")

def characterRemarks(names: List[String], remarks: List[String]) = <CharacterRemarks>
  { names zip remarks map { case (name, remark) => <Character name={name}>{remark}</Character> } }
</CharacterRemarks>

characterRemarks(names, remarks)


put ("April", "Tam O'Shanter", "Emily") into names
put ("Bubbly: I'm > Tam and <= Emily", <<Burns: "When chapman billies leave the street ...">>, "Short & shrift") into remarks
put (_tag: "CharacterRemarks") as tree into document
repeat for each item name in names
	insert (_tag: "Character", name: name, _children: item the counter of remarks) as tree into document's _children
end repeat
put document


require('XML::Mini::Document');

var students = [
                ["April",         "Bubbly: I'm > Tam and <= Emily"],
                ["Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""],
                ["Emily",         "Short & shrift"]
               ];

var doc   = %s'XML::Mini::Document'.new;
var root  = doc.getRoot;
var studs = root.createChild("CharacterRemarks");

students.each { |s|
    var stud = studs.createChild("Character");
    stud.attribute("name", s[0]);
    stud.text(s[1]);
};

print doc.toString;


lobby define: #remarks -> (
{'April' -> 'Bubbly: I\'m > Tam and <= Emily'.
'Tam O\'Shanter' -> 'Burns: "When chapman billies leave the street ..."'.
'Emily' -> 'Short & shrift'.
} as: Dictionary).

define: #writer -> (Xml Writer newOn: '' new writer).
writer inTag: 'CharacterRemarks' do:
  [| :w |
   lobby remarks keysAndValuesDo:
     [| :name :remark | w inTag: 'Character' do: [| :w | w ; remark] &attributes: {'name' -> name}].
   ].

inform: writer contents


proc xquote string {
    list [string map "' ' \\\" " < > > < & &" $string]
}
proc < {name attl args} {
    set res <$name
    foreach {att val} $attl {
        append res " $att='$val'"
    }
    if {[llength $args]} {
        append res >
        set sep ""
        foreach a $args {
            append res $sep $a
            set sep \n
        }
        append res </$name>
    } else {append res />}
    return $res
}
set cmd {< CharacterRemarks {}}
foreach {name comment} {
    April "Bubbly: I'm > Tam and <= Emily"
    "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\""
    Emily "Short & shrift"
} {
    append cmd " \[< Character {Name [xquote $name]} [xquote $comment]\]"
}
puts [eval $cmd]


$$ MODE TUSCRIPT
STRUCTURE xmloutput
DATA '<CharacterRemarks>'
DATA * '  <Character name="' names +'">' remarks +'</Character>'
DATA = '</CharacterRemarks>'
ENDSTRUCTURE
BUILD X_TABLE entitysubst=" >> > << < & & "
ERROR/STOP CREATE ("dest",seq-o,-std-)
ACCESS d: WRITE/ERASE/STRUCTURE  "dest" num,str
str="xmloutput"
  names=*
  DATA April
  DATA Tam O'Shanter
  DATA Emily
  remarks=*
  DATA Bubbly: I'm > Tam and <= Emily
  DATA Burns: "When chapman billies leave the street ..."
  DATA Short & shrift
  remarks=EXCHANGE(remarks,entitysubst)
WRITE/NEXT d
ENDACCESS d


Set objXMLDoc = CreateObject("msxml2.domdocument")

Set objRoot = objXMLDoc.createElement("CharacterRemarks")
objXMLDoc.appendChild objRoot

Call CreateNode("April","Bubbly: I'm > Tam and <= Emily")
Call CreateNode("Tam O'Shanter","Burns: ""When chapman billies leave the street ...""")
Call CreateNode("Emily","Short & shrift")

objXMLDoc.save("C:\Temp\Test.xml")

Function CreateNode(attrib_value,node_value)
	Set objNode = objXMLDoc.createElement("Character")
	objNode.setAttribute "name", attrib_value
	objNode.text = node_value
	objRoot.appendChild objNode
End Function


// Replace special characters with entities:
Replace("&", "&", BEGIN+ALL+NOERR)          // this must be the first replace!
Replace("<", "<", BEGIN+ALL+NOERR)
Replace(">", ">", BEGIN+ALL+NOERR)
Replace("'", "'", BEGIN+ALL+NOERR)
Replace('"', """, BEGIN+ALL+NOERR)

// Insert XML marking
BOF
IT("<CharacterRemarks>") IN
Repeat(ALL) {
    Search("^.", REGEXP+ERRBREAK)
    IT('  <Character name="')
    Replace('|T', '">')
    EOL IT('</Character>')
}
EOF
IT("</CharacterRemarks>") IN


Module XMLOutput
    Sub Main()
        Dim charRemarks As New Dictionary(Of String, String)
        charRemarks.Add("April", "Bubbly: I'm > Tam and <= Emily")
        charRemarks.Add("Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""")
        charRemarks.Add("Emily", "Short & shrift")

        Dim xml = <CharacterRemarks>
                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>
                  </CharacterRemarks>

        Console.WriteLine(xml)
    End Sub
End Module


var escapes = [
    ["&" , "&"], // must do this one first
    ["\"", """],
    ["'" , "'"],
    ["<" , "<"],
    [">" , ">"]
]

var xmlEscape = Fn.new { |s|
    for (esc in escapes) s = s.replace(esc[0], esc[1])
    return s
}

var xmlDoc = Fn.new { |names, remarks|
    var xml = "<CharacterRemarks>\n"
    for (i in 0...names.count) {
        var name = xmlEscape.call(names[i])
        var remark = xmlEscape.call(remarks[i])
        xml = xml + "    <Character name=\"%(name)\">%(remark)</Character>\n"
    }
    xml = xml + "</CharacterRemarks>"
    System.print(xml)
}

var names = ["April", "Tam O'Shanter", "Emily"]
var remarks = [
    "Bubbly: I'm > Tam and <= Emily",
    "Burns: \"When chapman billies leave the street ...\"",
    "Short & shrift"
]
xmlDoc.call(names, remarks)


code ChOut=8, CrLf=9, Text=12;
string 0;               \use zero-terminated strings

proc XmlOut(S);         \Output string in XML format
char S;
repeat  case S(0) of    \character entity substitutions
          ^<: Text(0, "<");
          ^>: Text(0, ">");
          ^&: Text(0, "&");
          ^": Text(0, """);
          ^': Text(0, "'")
        other ChOut(0, S(0));
        S:= S+1;
until S(0) = 0;

int Name, Remark, I;
[Name:= ["April",  "Tam O'Shanter",  "Emily"];
Remark:= ["Bubbly: I'm > Tam and <= Emily",
          "Burns: ^"When chapman billies leave the street ...^"",
          "Short & shrift"];
Text(0, "<CharacterRemarks>");  CrLf(0);
for I:= 0 to 3-1 do
        [Text(0, " <Character name=^"");
        XmlOut(Name(I));
        Text(0, "^">");
        XmlOut(Remark(I));
        Text(0, "</Character>");  CrLf(0);
        ];
Text(0, "</CharacterRemarks>");  CrLf(0);
]


let $names := ("April","Tam O'Shanter","Emily")
let $remarks := ("Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."',"Short & shrift")
return element CharacterRemarks {
                                  for $name at $count in $names
                                  return element Character {
                                                             attribute name { $name }
                                                            ,text { $remarks[$count] }
                                                            }
                                }


sign$ = "<,<,>,>,&,&"
dim sign$(1)
long = token(sign$, sign$(), ",")

sub substitute_all$(s$)
    local i

    for i = 1 to long step 2
        if s$ = sign$(i) return sign$(i + 1)
    next i
    return s$
end sub

sub xmlquote_all$(s$)
    local i, res$

    for i = 1 to len(s$)
        res$ = res$ + substitute_all$(mid$(s$, i, 1))
    next i
    return res$
end sub

sub xml_CharacterRemarks$(datos$())
    local res$, i, long

    long = arraysize(datos$(), 1)

    res$ = "<CharacterRemarks>\n"

    for i = 1 to long
        res$ = res$ + "  <CharacterName=\"" + xmlquote_all$(datos$(i, 1)) + "\">" + xmlquote_all$(datos$(i, 2)) + "</Character>\n"
    next i
    return res$ + "</CharacterRemarks>\n"
end sub

data "April", "Bubbly: I'm > Tam and <= Emily"
data "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""
data "Emily", "Short & shrift"

dim testset$(3, 2)

for i = 1 to 3
    read testset$(i, 1), testset$(i, 2)
next i

print xml_CharacterRemarks$(testset$())


fcn xmlEscape(text){
   text.replace(" &"," &")  .replace(" \""," "")
       .replace(" '"," '") .replace(" <"," <") .replace(" >"," >")
}
fcn toXML(as,bs){
   xml:=Sink("<CharacterRemarks>\n");
   as.zipWith('wrap(a,b){
      xml.write("  <Character name=\"",xmlEscape(a),"\">",
		xmlEscape(b),"</Character>\n");
   },bs);
   xml.write("</CharacterRemarks>\n").close();
}

toXML(T("April", "Tam O'Shanter", "Emily"),
       T("Bubbly: I'm > Tam and <= Emily",
         0'|Burns: "When chapman billies leave the street ..."|,
	 "Short & shrift"))
.print();


:start:
I :argv.len != 5
   print(‘Usage : #. < Followed by level, id, source string and description>’.format(:argv[0]))
E
   os:(‘EventCreate /t #. /id #. /l APPLICATION /so #. /d "#."’.format(:argv[1], :argv[2], :argv[3], :argv[4]))


; By ABCza, http://www.autohotkey.com/board/topic/76170-function-send-windows-log-events/
h := RegisterForEvents("AutoHotkey")
SendWinLogEvent(h, "Test Message")
DeregisterForEvents(h)

/*
--------------------------------------------------------------------------------------------------------------------------------
FUNCTION: SendWinLogEvent
--------------------------------------------------------------------------------------------------------------------------------
Writes an entry at the end of the specified Windows event log. Returns nonzero if the function succeeds or zero if it fails.

PARAMETERS:
~~~~~~~~~~~
hSource		- Handle to a previously registered events source with RegisterForEvents.
evType		- EVENTLOG_SUCCESS			:= 0x0000
			  EVENTLOG_AUDIT_FAILURE	:= 0x0010
			  EVENTLOG_AUDIT_SUCCESS	:= 0x0008
			  EVENTLOG_ERROR_TYPE		:= 0x0001
			  EVENTLOG_INFORMATION_TYPE	:= 0x0004
			  EVENTLOG_WARNING_TYPE		:= 0x0002
evId		- Event ID, can be any dword value.
evCat		- Any value, used to organize events in categories.
pStrings	- A continuation section with newline separated strings (each max 31839 chars).
pData		- A buffer containing the binary data.
--------------------------------------------------------------------------------------------------------------------------------
SYSTEM CALLS, STRUCTURES AND INFO:
--------------------------------------------------------------------------------------------------------------------------------
ReportEvent										- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx
Event Identifiers								- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363651(v=vs.85).aspx
Event categories								- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363649(v=vs.85).aspx
--------------------------------------------------------------------------------------------------------------------------------
*/
SendWinLogEvent(hSource, String="", evType=0x0004, evId=0x03EA, evCat=0, pData=0) {
	Ptr := A_PtrSize ? "Ptr" : "UInt"
	LPCtSTRs := A_PtrSize ? "Ptr*" : "UInt"
	StringPut := A_IsUnicode ? "StrPut" : "StrPut2"

	; Reserve and initialise space for the event message.
	VarSetCapacity(eventMessage, StrLen(String), 0)
	%StringPut%(String, &eventMessage, A_IsUnicode ? "UTF-16" : "")
	r := DllCall("Advapi32.dll\ReportEvent" (A_IsUnicode ? "W" : "A")
		, UInt, hSource			; handle
		, UShort, evType		; WORD, eventlog_information_type
		, UShort, evCat			; WORD, category
		, UInt, evId			; DWORD, event ID, 0x03EA
		, Ptr, 0			; PSID, ptr to user security ID
		, UShort, 1			; WORD, number of strings
		, UInt, VarSetCapacity(pData)	; DWORD, data size
		, LPCtSTRs, &eventMessage	; LPCTSTR*, ptr to a buffer ...
		, Ptr, (VarSetCapacity(pData)) ? &pData : 0 )	; ptr to a buffer of binary data

	; Release memory.
	VarSetCapacity(eventMessage, 0)

	Return r
}
/*
--------------------------------------------------------------------------------------------------------------------------------
FUNCTION: RegisterForEvents
--------------------------------------------------------------------------------------------------------------------------------
Registers the application to send Windows log events. Returns a handle to the registered source.

PARAMETERS:
~~~~~~~~~~~
logName	 - Can be "Application", "System" or a custom log name.
--------------------------------------------------------------------------------------------------------------------------------
SYSTEM CALLS, STRUCTURES AND INFO:
--------------------------------------------------------------------------------------------------------------------------------
RegisterEventSource							- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363678(v=VS.85).aspx
Event Sources								- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363661(v=VS.85).aspx
--------------------------------------------------------------------------------------------------------------------------------
*/
RegisterForEvents(logName) {
	Return DllCall("Advapi32.dll\RegisterEventSource" (A_IsUnicode ? "W" : "A")
		, UInt, 0				; LPCTSTR, Local computer
		, Str, logName)			; LPCTSTR Source name
}
/*
--------------------------------------------------------------------------------------------------------------------------------
FUNCTION: DeregisterForEvents
--------------------------------------------------------------------------------------------------------------------------------
Deregisters the previously registered application.

PARAMETERS:
~~~~~~~~~~~
hSource	 - Handle to a registered source.
--------------------------------------------------------------------------------------------------------------------------------
SYSTEM CALLS, STRUCTURES AND INFO:
--------------------------------------------------------------------------------------------------------------------------------
DeregisterEventSource						- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363642(v=vs.85).aspx
Event Sources								- http://msdn.microsoft.com/en-us/library/windows/desktop/aa363661(v=VS.85).aspx
--------------------------------------------------------------------------------------------------------------------------------
*/
DeregisterForEvents(hSource) {
	IfNotEqual, hSource, 0, Return DllCall( "Advapi32.dll\DeregisterEventSource"
		, UInt, hSource )
}

; StrPut for AutoHotkey Basic
StrPut2(String, Address="", Length=-1, Encoding=0)
{
	; Flexible parameter handling:
	if Address is not integer		 ; StrPut(String [, Encoding])
		Encoding := Address,	Length := 0,	Address := 1024
	else if Length is not integer	 ; StrPut(String, Address, Encoding)
		Encoding := Length,	Length := -1

	; Check for obvious errors.
	if (Address+0 < 1024)
		return

	; Ensure 'Encoding' contains a numeric identifier.
	if Encoding = UTF-16
		Encoding = 1200
	else if Encoding = UTF-8
		Encoding = 65001
	else if SubStr(Encoding,1,2)="CP"
		Encoding := SubStr(Encoding,3)

	if !Encoding ; "" or 0
	{
		; No conversion required.
		char_count := StrLen(String) + 1 ; + 1 because generally a null-terminator is wanted.
		if (Length)
		{
			; Check for sufficient buffer space.
			if (StrLen(String) <= Length || Length == -1)
			{
				if (StrLen(String) == Length)
					; Exceptional case: caller doesn't want a null-terminator.
					char_count--
				; Copy the string, including null-terminator if requested.
				DllCall("RtlMoveMemory", "uint", Address, "uint", &String, "uint", char_count)
			}
			else
				; For consistency with the sections below, don't truncate the string.
				char_count = 0
		}
		;else: Caller just wants the the required buffer size (char_count), which will be returned below.
	}
	else if Encoding = 1200 ; UTF-16
	{
		; See the 'else' to this 'if' below for comments.
		if (Length <= 0)
		{
			char_count := DllCall("MultiByteToWideChar", "uint", 0, "uint", 0, "uint", &String, "int", StrLen(String), "uint", 0, "int", 0) + 1
			if (Length == 0)
				return char_count
			Length := char_count
		}
		char_count := DllCall("MultiByteToWideChar", "uint", 0, "uint", 0, "uint", &String, "int", StrLen(String), "uint", Address, "int", Length)
		if (char_count && char_count < Length)
			NumPut(0, Address+0, char_count++*2, "UShort")
	}
	else if Encoding is integer
	{
		; Convert native ANSI string to UTF-16 first.	NOTE - wbuf_len includes the null-terminator.
		VarSetCapacity(wbuf, 2 * wbuf_len := StrPut2(String, "UTF-16")), StrPut2(String, &wbuf, "UTF-16")

		; UTF-8 and some other encodings do not support this flag.	Avoid it for UTF-8
		; (which is probably common) and rely on the fallback behaviour for other encodings.
		flags := Encoding=65001 ? 0 : 0x400	; WC_NO_BEST_FIT_CHARS
		if (Length <= 0) ; -1 or 0
		{
			; Determine required buffer size.
			loop 2 {
				char_count := DllCall("WideCharToMultiByte", "uint", Encoding, "uint", flags, "uint", &wbuf, "int", wbuf_len, "uint", 0, "int", 0, "uint", 0, "uint", 0)
				if (char_count || A_LastError != 1004) ; ERROR_INVALID_FLAGS
					break
				flags := 0	; Try again without WC_NO_BEST_FIT_CHARS.
			}
			if (!char_count)
				return ; FAIL
			if (Length == 0) ; Caller just wants the required buffer size.
				return char_count
			; Assume there is sufficient buffer space and hope for the best:
			Length := char_count
		}
		; Convert to target encoding.
		char_count := DllCall("WideCharToMultiByte", "uint", Encoding, "uint", flags, "uint", &wbuf, "int", wbuf_len, "uint", Address, "int", Length, "uint", 0, "uint", 0)
		; Since above did not null-terminate, check for buffer space and null-terminate if there's room.
		; It is tempting to always null-terminate (potentially replacing the last byte of data),
		; but that would exclude this function as a means to copy a string into a fixed-length array.
		if (char_count && char_count < Length)
			NumPut(0, Address+0, char_count++, "Char")
		; else no space to null-terminate; or conversion failed.
	}
	; Return the number of characters copied.
	return char_count
}


# syntax: GAWK -f WRITE_TO_WINDOWS_EVENT_LOG.AWK
BEGIN {
    write("INFORMATION",1,"Rosetta Code")
    exit (errors == 0) ? 0 : 1
}
function write(type,id,description,  cmd,esf) {
    esf = errors # errors so far
    cmd = sprintf("EVENTCREATE.EXE /T %s /ID %d /D \"%s\" >NUL",type,id,description)
    printf("%s\n",cmd)
    if (toupper(type) !~ /^(SUCCESS|ERROR|WARNING|INFORMATION)$/) { error("/T is invalid") }
    if (id+0 < 1 || id+0 > 1000) { error("/ID is invalid") }
    if (description == "") { error("/D is invalid") }
    if (errors == esf) {
      system(cmd)
    }
    return(errors)
}
function error(message) { printf("error: %s\n",message) ; errors++ }


@echo off
EventCreate /t ERROR /id 123 /l SYSTEM /so "A Batch File" /d "This is found in system log."
EventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d "This is found in apps log"


      INSTALL @lib$+"COMLIB"
      PROC_cominitlcid(1033)

      WshShell% = FN_createobject("WScript.Shell")
      PROC_callmethod(WshShell%, "LogEvent(0, ""Test from BBC BASIC"")")

      PROC_releaseobject(WshShell%)
      PROC_comexit


#include<stdlib.h>
#include<stdio.h>

int main(int argC,char* argV[])
{
	char str[1000];

	if(argC!=5)
		printf("Usage : %s < Followed by level, id, source string and description>",argV[0]);
	else{
		sprintf(str,"EventCreate /t %s /id %s /l APPLICATION /so %s /d \"%s\"",argV[1],argV[2],argV[3],argV[4]);
		system(str);
	}

	return 0;
}


using System.Diagnostics;

namespace RC
{
  internal class Program
  {
    public static void Main()
    {
      string sSource  = "Sample App";
      string sLog     = "Application";
      string sEvent   = "Hello from RC!";

      if (!EventLog.SourceExists(sSource))
        EventLog.CreateEventSource(sSource, sLog);

      EventLog.WriteEntry(sSource, sEvent);
      EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information);
    }
  }
}


#include <iostream>
#include <sstream>

int main(int argc, char *argv[]) {
    using namespace std;

#if _WIN32
    if (argc != 5) {
        cout << "Usage : " << argv[0] << " (type)  (id)  (source string) (description>)\n";
        cout << "    Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n";
    } else {
        stringstream ss;
        ss << "EventCreate /t " << argv[1] << " /id " << argv[2] << " /l APPLICATION /so " << argv[3] << " /d \"" << argv[4] << "\"";
        system(ss.str().c_str());
    }
#else
    cout << "Not implemented for *nix, only windows.\n";
#endif

    return 0;
}


(use 'clojure.java.shell)
(sh "eventcreate" "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example")


import std.process;
import std.stdio;

void main() {
    auto cmd = executeShell(`EventCreate /t INFORMATION /id 123 /l APPLICATION /so Dlang /d "Rosetta Code Example"`);

    if (cmd.status == 0) {
        writeln("Output: ", cmd.output);
    } else {
        writeln("Failed to execute command, status=", cmd.status);
    }
}


program WriteToEventLog;

{$APPTYPE CONSOLE}

uses Windows;

procedure WriteLog(aMsg: string);
var
  lHandle: THandle;
  lMessagePtr: Pointer;
begin
  lMessagePtr := PChar(aMsg);
  lHandle := RegisterEventSource(nil, 'Logger');
  if lHandle > 0 then
  begin
    try
      ReportEvent(lHandle, 4 {Information}, 0, 0, nil, 1, 0, @lMessagePtr, nil);
    finally
      DeregisterEventSource(lHandle);
    end;
  end;
end;

begin
  WriteLog('Message to log.');
end.


use log = new System.Diagnostics.EventLog()
log.Source <- "Sample Application"
log.WriteEntry("Entered something in the Application Eventlog!")


package main

import (
    "fmt"
    "os/exec"
)

func main() {
    command := "EventCreate"
    args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
        "/SO", "Go", "/D", "\"Rosetta Code Example\""}
    cmd := exec.Command(command, args...)
    err := cmd.Run()
    if err != nil {
        fmt.Println(err)
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class WriteToWindowsEventLog {
    public static void main(String[] args) throws IOException, InterruptedException {
        String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
        if (!osName.startsWith("WINDOWS")) {
            System.err.println("Not windows");
            return;
        }

        Process process = Runtime.getRuntime().exec("EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \"Rosetta Code Example\"");
        process.waitFor(10, TimeUnit.SECONDS);
        int exitValue = process.exitValue();
        System.out.printf("Process exited with value %d\n", exitValue);
        if (exitValue != 0) {
            InputStream errorStream = process.getErrorStream();
            String result = new BufferedReader(new InputStreamReader(errorStream))
                .lines()
                .collect(Collectors.joining("\n"));
            System.err.println(result);
        }
    }
}


 cmd = "eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\""
 Base.run(`$cmd`)


// version 1.1.4-3

fun main(args: Array<String>) {
    val command = "EventCreate" +
                  " /t INFORMATION" +
                  " /id 123" +
                  " /l APPLICATION" +
                  " /so Kotlin" +
                  " /d \"Rosetta Code Example\""

    Runtime.getRuntime().exec(command)
}


shell = xtra("Shell").new()
props = [:]
props["operation"] = "runas"
props["parameters"] = "/t INFORMATION /id 123 /l APPLICATION /so Lingo /d "&QUOTE&"Rosetta Code Example"&QUOTE
shell.shell_exec("EventCreate", props)


use strict;
use warnings;

use Win32::EventLog;
my $handle = Win32::EventLog->new("Application");

my $event = {
	Computer 	=>	$ENV{COMPUTERNAME},
	Source		=> 	'Rosettacode',
	EventType 	=> 	EVENTLOG_INFORMATION_TYPE,
	Category  	=> 	'test',
	EventID 	=> 	0,
	Data 		=> 	'a test for rosettacode',
	Strings 	=> 	'a string test for rosettacode',
};
$handle->Report($event);


requires(WINDOWS) -- (as in this will not work on Linux or p2js, duh)
without js -- (as above, also prevent pointless attempts to transpile)
system(`eventcreate /T INFORMATION /ID 123 /D "Rosetta Code Write to Windows event log task example"`)


: (call 'logger "This is a test")
-> T

: (call 'logger "This" 'is "another" 'test)
-> T


# Create Event Log object
$EventLog=new-object System.Diagnostics.EventLog("Application")
#Declare Event Source; must be 'registered' with Windows
$EventLog.Source="Application" # It is possible to register a new source (see Note2)
# Setup the Event Types; you don't have to use them all, but I'm including all the possibilities for reference
$infoEvent=[System.Diagnostics.EventLogEntryType]::Information
$errorEvent=[System.Diagnostics.EventLogEntryType]::Error
$warningEvent=[System.Diagnostics.EventLogEntryType]::Warning
$successAuditEvent=[System.Diagnostics.EventLogEntryType]::SuccessAudit
$failureAuditEvent=[System.Diagnostics.EventLogEntryType]::FailureAudit

# Write the event in the format "Event test",EventType,EventID
$EventLog.WriteEntry("My Test Event",$infoevent,70)


Procedure WriteToLog(Event_App$,EventMessage$,EvenetType,Computer$)

  Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray
  Protected lprawdata=@EventMessage$, rawdata=Len(EventMessage$), Result
  Protected lLogAPIRetVal.l = RegisterEventSource_(Computer$, Event_App$)

  If lLogAPIRetVal
    lReturnX = ReportEvent_(lLogAPIRetVal,EvenetType,0,CMessageTyp,0,wNumStrings,rawdata,lparray,lprawdata
    DeregisterEventSource_(lLogAPIRetVal)
    Result=#True
  EndIf

  ProcedureReturn Result
EndProcedure


import win32api
import win32con
import win32evtlog
import win32security
import win32evtlogutil

ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]

applicationName = "My Application"
eventID = 1
category = 5	# Shell
myType = win32evtlog.EVENTLOG_WARNING_TYPE
descr = ["A warning", "An even more dire warning"]
data = "Application\0Data".encode("ascii")

win32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category,
	eventType=myType, strings=descr, data=data, sid=my_sid)


#lang racket
(log-warning "Warning: nothing went wrong.")


given $*DISTRO {
    when .is-win {
        my $cmd = "eventcreate /T INFORMATION /ID 123 /D \"Bla de bla bla bla\"";
        run($cmd);
    }
    default { # most POSIX environments
        use Log::Syslog::Native;
        my $logger = Log::Syslog::Native.new(facility => Log::Syslog::Native::User);
        $logger.info("[$*PROGRAM-NAME pid=$*PID user=$*USER] Just thought you might like to know.");
    }
}


/*REXX program writes a "record" (event) to the  (Microsoft)  Windows event log.        */

    eCMD = 'EVENTCREATE'                         /*name of the command that'll be used. */
    type = 'INFORMATION'                         /*one of:  ERROR  WARNING  INFORMATION */
      id =  234                                  /*in range:  1 ───►  1000  (inclusive).*/
 logName = 'APPLICATION'                         /*information about what this is.      */
  source = 'REXX'                                /*     "        "   who's doing this.  */
    desc = 'attempting to add an entry for a Rosetta Code demonstration.'
    desc = '"'  ||  desc  ||  '"'                /*enclose description in double quotes.*/

eCMD  '/T'  type       "/ID"  id       '/L'  logName       "/SO"  source       '/D'  desc

                                                 /*stick a fork in it,  we're all done. */


require 'win32/eventlog'
logger = Win32::EventLog.new
logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry")


#[cfg(windows)]
mod bindings {
    ::windows::include_bindings!();
}

#[cfg(windows)]
use bindings::{
    Windows::Win32::Security::{
        GetTokenInformation, OpenProcessToken, PSID, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS,
        TOKEN_USER,
    },
    Windows::Win32::SystemServices::{
        GetCurrentProcess, OpenEventLogA, ReportEventA, ReportEvent_wType, HANDLE, PSTR,
    },
};

#[cfg(windows)]
fn main() -> windows::Result<()> {
    let ph = unsafe { GetCurrentProcess() };
    let mut th: HANDLE = HANDLE(0);
    unsafe { OpenProcessToken(ph, TOKEN_ACCESS_MASK::TOKEN_QUERY, &mut th) }.ok()?;

    // Determine the required buffer size, ignore ERROR_INSUFFICIENT_BUFFER
    let mut length = 0_u32;
    unsafe {
        GetTokenInformation(
            th,
            TOKEN_INFORMATION_CLASS::TokenUser,
            std::ptr::null_mut(),
            0,
            &mut length,
        )
    }
    .ok()
    .unwrap_err();

    // Retrieve the user token.
    let mut token_user_bytes = vec![0u8; length as usize];
    unsafe {
        GetTokenInformation(
            th,
            TOKEN_INFORMATION_CLASS::TokenUser,
            token_user_bytes.as_mut_ptr().cast(),
            length,
            &mut length,
        )
    }
    .ok()?;

    // Extract the pointer to the user SID.
    let user_sid: PSID = unsafe { (*token_user_bytes.as_ptr().cast::<TOKEN_USER>()).User.Sid };

    // use the Application event log
    let event_log_handle = unsafe { OpenEventLogA(PSTR::default(), "Application") };

    let mut event_msg = PSTR(b"Hello in the event log\0".as_ptr() as _);
    unsafe {
        ReportEventA(
            HANDLE(event_log_handle.0),               //h_event_log: T0__,
            ReportEvent_wType::EVENTLOG_WARNING_TYPE, // for type use EVENTLOG_WARNING_TYPE w_type: u16,
            5,                                        // for category use "Shell" w_category: u16,
            1,                                        // for ID use 1  dw_event_id: u32,
            user_sid,                                 // lp_user_sid: *mut c_void,
            1,                                        // w_num_strings: u16,
            0,                                        // dw_data_size: u32,
            &mut event_msg,                           // lp_strings: *mut PSTR,
            std::ptr::null_mut(),                     // lp_raw_data: *mut c_void,
        )
    }
    .ok()?;

    Ok(())
}

#[cfg(not(windows))]
fn main() {
    println!("Not implemented");
}


object RegisterWinLogEvent extends App {

  import sys.process._

  def eventCreate= Seq("EVENTCREATE", "/T", "SUCCESS", "/id", "123", "/l", "APPLICATION", "/so", "Scala RegisterWinLogEvent", "/d", "Rosetta Code Example"  ).!!

  println(eventCreate)

  println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")

}


OS.Process.system "logger \"Log event\" " ;


package require twapi

# This command handles everything; use “-type error” to write an error message
twapi::eventlog_log "My Test Event" -type info


Sub write_event(event_type,msg)
	Set objShell = CreateObject("WScript.Shell")
	Select Case event_type
		Case "SUCCESS"
			n = 0
		Case "ERROR"
			n = 1
		Case "WARNING"
			n = 2
		Case "INFORMATION"
			n = 4
		Case "AUDIT_SUCCESS"
			n = 8
		Case "AUDIT_FAILURE"
			n = 16
	End Select
	objShell.LogEvent n, msg
	Set objShell = Nothing
End Sub

Call write_event("INFORMATION","This is a test information.")


/* write_to_windows_event_log.wren */

class Windows {
    foreign static eventCreate(args)
}

var args = [
    "/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
    "/SO", "Wren", "/D", "\"Rosetta Code Example\""
].join(" ")

Windows.eventCreate(args)


zkl: System.cmd(0'|eventcreate "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example"|)


INCLUDE "H6:REALMATH.ACT"

REAL one

PROC PutBigPixel(INT x,y,col)
  IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN
    y==LSH 2
    IF col<0 THEN col=0
    ELSEIF col>15 THEN col=15 FI
    Color=col
    Plot(x,y)
    DrawTo(x,y+3)
  FI
RETURN

INT FUNC Abs(INT x)
  IF x<0 THEN RETURN (-x) FI
RETURN (x)

PROC Swap(INT POINTER a,b)
  INT tmp

  tmp=a^ a^=b^ b^=tmp
RETURN

PROC Line(INT x1,y1,x2,y2,col)
  INT x,y,dx,dy,c
  INT POINTER px,py
  REAL rx,ry,grad,rcol,tmp1,tmp2

  dx=Abs(x2-x1)
  dy=Abs(y2-y1)
  IF dy>dx THEN
    Swap(@x1,@y1)
    Swap(@x2,@y2)
    [email protected] [email protected]
  ELSE
    [email protected] [email protected]
  FI

  IF x1>x2 THEN
    Swap(@x1,@x2)
    Swap(@y1,@y2)
  FI

  x=x2-x1
  IF x=0 THEN x=1 FI
  IntToRealForNeg(x,rx)
  IntToRealForNeg(y2-y1,ry)
  RealDiv(ry,rx,grad)

  IntToRealForNeg(y1,ry)
  IntToReal(col,rcol)
  FOR x=x1 TO x2
  DO
    Frac(ry,tmp1)
    IF IsNegative(tmp1) THEN
      RealAdd(one,tmp1,tmp2)
      RealAssign(tmp2,tmp1)
    FI
    RealMult(rcol,tmp1,tmp2)
    c=Round(tmp2)
    y=Floor(ry)
    PutBigPixel(px^,py^,col-c)
    y==+1
    PutBigPixel(px^,py^,c)
    RealAdd(ry,grad,tmp1)
    RealAssign(tmp1,ry)
  OD
RETURN

PROC Main()
  BYTE CH=$02FC ;Internal hardware value for last key pressed
  REAL tmp,c
  BYTE i,x1,y1,x2,y2

  MathInit()
  IntToReal(1,one)

  Graphics(9)
  FOR i=0 TO 11
  DO
    Line(0,i*4,38,1+i*5,15)
    Line(40+i*4,0,41+i*6,47,15)
  OD

  DO UNTIL CH#$FF OD
  CH=$FF
RETURN