XML/DOM serialization: Difference between revisions

From Rosetta Code
< XML
Content added Content deleted
mNo edit summary
(Added FreeBASIC)
 
(165 intermediate revisions by 72 users not shown)
Line 1: Line 1:
{{task|XML}}
[http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=186 free jazz ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=171 order clomid] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=144 cheap xanax] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=236 free tracfone ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=180 flexeril] [http://wc1.worldcrossing.com/WebX/.1de609f3 midi ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a2c but ultram] [http://wc1.worldcrossing.com/WebX/.1de60a34 sony ericsson ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a0d wwe ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=207 real ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=110 nokia ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=220 punk ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=203 funny ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=173 cool ringtones] [http://wc1.worldcrossing.com/WebX/.1de609eb free funny ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=83 didrex online] [http://wc1.worldcrossing.com/WebX/.1de60a21 paxil online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=172 lorazepam online] [http://wc1.worldcrossing.com/WebX/.1de60a1a mtv ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=71 buy alprazolam] [http://news.engin.brown.edu/forums/thread-view.asp?tid=190 pharmacy online online] [http://wc1.worldcrossing.com/WebX/.1de60a03 free sony ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=201 free ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a0b vigrx online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=211 free polyphonic ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=358 mp3 ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a23 free polyphonic ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=213 polyphonic ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=150 order tramadol] [http://news.engin.brown.edu/forums/thread-view.asp?tid=163 cheap adipex] [http://wc1.worldcrossing.com/WebX/.1de60a2b ultracet] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=219 cheap viagra] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=82 diazepam online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=185 cheap zoloft] [http://news.engin.brown.edu/forums/thread-view.asp?tid=192 vigrx] [http://wc1.worldcrossing.com/WebX/.1de60a1f lisinopril online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=114 cheap pharmacy online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=75 celexa online] [http://wc1.worldcrossing.com/WebX/.1de60a05 free sprint ringtones] [http://wc1.worldcrossing.com/WebX/.1de609e4 clonazepam online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=353 online levitra] [http://wc1.worldcrossing.com/WebX/.1de60a27 cheap sildenafil] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=140 cheap vicodin] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=337 xanax online] [http://wc1.worldcrossing.com/WebX/.1de60a2d cheap valium] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=206 cheap pharmacy online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=126 cheap sildenafil] [http://news.engin.brown.edu/forums/thread-view.asp?tid=174 cheap wellbutrin] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=160 order adipex] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=221 vicodin online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=143 wwe ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=70 alltel ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=230 verizon ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=102 midi ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=118 buy prozac] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=189 but lipitor] [http://news.engin.brown.edu/forums/thread-view.asp?tid=218 sony ericsson ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=232 free sony ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=161 cheap albuterol] [http://news.engin.brown.edu/forums/thread-view.asp?tid=161 cheap viagra] [http://wc1.worldcrossing.com/WebX/.1de609e1 carisoprodol online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=128 free sony ericsson ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a24 propecia online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=200 nexium online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=191 lorazepam online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=197 flexeril online] [http://wc1.worldcrossing.com/WebX/.1de60a07 tracfone ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=182 clomid online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=205 paxil online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=208 free motorola ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=216 zyban online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=120 qwest ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=109 nextel ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=79 cheap clonazepam] [http://news.engin.brown.edu/forums/thread-view.asp?tid=211 music ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=226 tramadol online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=333 cheap soma] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=81 buy cyclobenzaprine] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=332 cheap tramadol] [http://news.engin.brown.edu/forums/thread-view.asp?tid=160 ativan online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=68 adipex online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=108 nexium online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=167 clonazepam online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=90 cheap hgh] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=132 cheap tenuate] [http://wc1.worldcrossing.com/WebX/.1de60a32 zoloft online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=223 midi ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=166 order alprazolam] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=72 cheap ambien] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=241 free sony ericsson ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=184 cheap lisinopril] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=194 free midi ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=74 carisoprodol online] [http://wc1.worldcrossing.com/WebX/.1de609f8 nokia ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=182 free funny ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=176 cheap didrex] [http://news.engin.brown.edu/forums/thread-view.asp?tid=196 buy hgh] [http://wc1.worldcrossing.com/WebX/.1de60a10 didrex online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=129 free sony ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=339 order ultram] [http://wc1.worldcrossing.com/WebX/.1de609ec buy hgh] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=85 free ericsson ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=156 fioricet] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=76 cialis online] [http://wc1.worldcrossing.com/WebX/.1de60a1e flexeril online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=336 carisoprodol online] [http://wc1.worldcrossing.com/WebX/.1de609ff free real ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=198 cheap hoodia] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=165 but ambien] [http://news.engin.brown.edu/forums/thread-view.asp?tid=186 lipitor online] [http://wc1.worldcrossing.com/WebX/.1de609fa free online pharmacy] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=88 free free ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=146 buy zanaflex] [http://news.engin.brown.edu/forums/thread-view.asp?tid=153 cheap phentermine] [http://wc1.worldcrossing.com/WebX/.1de60a11 diethylpropion online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=240 buy soma] [http://news.engin.brown.edu/forums/thread-view.asp?tid=210 free sprint ringtones] [http://wc1.worldcrossing.com/WebX/.1de609e7 cheap diazepam] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=125 sharp ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=170 hydrocodone online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=347 adipex] [http://news.engin.brown.edu/forums/thread-view.asp?tid=155 buy xanax] [http://wc1.worldcrossing.com/WebX/.1de609e3 clomid online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=356 tracfone ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=222 free sharp ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=98 lisinopril] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=223 cheap wellbutrin] [http://wc1.worldcrossing.com/WebX/.1de60a15 free kyocera ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=362 free motorola ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=115 phentermine online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=215 buy zoloft] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=167 cheap carisoprodol] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=164 alprazolam online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=177 diethylpropion online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=200 nokia ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=69 cheap albuterol] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=357 free funny ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=334 valium online] [http://wc1.worldcrossing.com/WebX/.1de60a29 tramadol online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=338 fioricet] [http://wc1.worldcrossing.com/WebX/.1de60a09 viagra online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=124 free samsung ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=198 free mtv ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=164 order norco] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=199 free music ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=166 buy ativan] [http://news.engin.brown.edu/forums/thread-view.asp?tid=188 tenuate online] [http://wc1.worldcrossing.com/WebX/.1de60a17 buy lipitor] [http://wc1.worldcrossing.com/WebX/.1de60a12 ericsson ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=151 order soma] [http://wc1.worldcrossing.com/WebX/.1de609df ambien online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=231 order rivotril] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=343 cialis] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=134 tramadol online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=227 ericsson ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=228 mtv ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=177 propecia online] [http://wc1.worldcrossing.com/WebX/.1de60a14 free jazz ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=187 kyocera ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=345 viagra online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=348 but norco] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=162 alltel ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=193 zanaflex online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=196 free motorola ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=139 cheap viagra] [http://news.engin.brown.edu/forums/thread-view.asp?tid=191 cheap lortab] [http://wc1.worldcrossing.com/WebX/.1de60a1b music ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a19 free mp3 ringtones] [http://wc1.worldcrossing.com/WebX/.1de609dc buy albuterol] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=351 buy clonazepam] [http://news.engin.brown.edu/forums/thread-view.asp?tid=171 ambien online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=173 order xenical] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=121 free real ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a20 nexium online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=142 wellbutrin] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=130 sonyericsson ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a0e cheap celexa] [http://news.engin.brown.edu/forums/thread-view.asp?tid=158 diazepam online] [http://wc1.worldcrossing.com/WebX/.1de609f7 nextel ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a28 soma online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=197 free mp3 ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=184 hoodia online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=359 free nextel ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=165 cheap vicodin] [http://wc1.worldcrossing.com/WebX/.1de60a01 free sagem ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=217 punk ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=117 propecia online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=195 mono ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=116 free polyphonic ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=96 cheap levitra] [http://news.engin.brown.edu/forums/thread-view.asp?tid=224 free wwe ringtones] [http://wc1.worldcrossing.com/WebX/.1de609f0 cheap lorazepam] [http://news.engin.brown.edu/forums/thread-view.asp?tid=209 free samsung ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a31 zanaflex online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=203 norco] [http://news.engin.brown.edu/forums/thread-view.asp?tid=178 buy nexium] [http://news.engin.brown.edu/forums/thread-view.asp?tid=157 ultram online] [http://wc1.worldcrossing.com/WebX/.1de609ed hoodia online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=183 cheap hgh] [http://wc1.worldcrossing.com/WebX/.1de609e5 free cool ringtones] {{task}}


Create a simple DOM and having it serialize to:
Create a simple DOM and having it serialize to:
Line 10: Line 10:
</root>
</root>


=={{header|AArch64 Assembly}}==
==[[JavaScript]]==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
[[Category:JavaScript]]
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program createXml64.s */
/* install package libxml++2.6-dev */
/* link with gcc option -I/usr/include/libxml2 -lxml2 */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndpgm: .asciz "Normal end of program.\n"
szFileName: .asciz "file1.xml"
szFileMode: .asciz "w"
szMessError: .asciz "Error detected !!!!. \n"
szVersDoc: .asciz "1.0"
szLibRoot: .asciz "root"
szLibElement: .asciz "element"
szText: .asciz "some text here"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszVersDoc
bl xmlNewDoc // create doc
mov x19,x0 // doc address
mov x0,#0
ldr x1,qAdrszLibRoot
bl xmlNewNode // create root node
cbz x0,99f
mov x20,x0 // node root address
mov x0,x19
mov x1,x20
bl xmlDocSetRootElement
mov x0,#0
ldr x1,qAdrszLibElement
bl xmlNewNode // create element node
mov x21,x0 // node element address
ldr x0,qAdrszText
bl xmlNewText // create text
mov x22,x0 // text address
mov x0,x21 // node element address
mov x1,x22 // text address
bl xmlAddChild // add text to element node
mov x0,x20 // node root address
mov x1,x21 // node element address
bl xmlAddChild // add node elemeny to root node
ldr x0,qAdrszFileName
ldr x1,qAdrszFileMode
bl fopen // file open
cmp x0,#0
blt 99f
mov x23,x0 // File descriptor
mov x1,x19 // doc
mov x2,x20 // root
bl xmlElemDump // write xml file
cmp x0,#0
blt 99f
mov x0,x23
bl fclose // file close
mov x0,x19
bl xmlFreeDoc
bl xmlCleanupParser
ldr x0,qAdrszMessEndpgm
bl affichageMess
b 100f
99: // error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrszMessEndpgm: .quad szMessEndpgm
qAdrszVersDoc: .quad szVersDoc
qAdrszLibRoot: .quad szLibRoot
qAdrszLibElement: .quad szLibElement
qAdrszText: .quad szText
qAdrszFileName: .quad szFileName
qAdrszFileMode: .quad szFileMode
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>

=={{header|ABAP}}==
<syntaxhighlight lang="abap">
DATA: xml_string TYPE string.

DATA(xml) = cl_ixml=>create( ).
DATA(doc) = xml->create_document( ).
DATA(root) = doc->create_simple_element( name = 'root'
parent = doc ).

doc->create_simple_element( name = 'element'
parent = root
value = 'Some text here' ).

DATA(stream_factory) = xml->create_stream_factory( ).
DATA(stream) = stream_factory->create_ostream_cstring( string = xml_string ).
DATA(renderer) = xml->create_renderer( document = doc
ostream = stream ).
stream->set_pretty_print( abap_true ).
renderer->render( ).

cl_demo_output=>display_text( xml_string ).
</syntaxhighlight>

Output:
<pre><?xml version="1.0" encoding="utf-16"?>
<root>
<element>Some text here</element>
</root></pre>

=={{header|Ada}}==
{{works with|GNAT}}

Uses [http://libre.adacore.com/libre/tools/xmlada/ XML/Ada] from AdaCore.

<syntaxhighlight lang="ada">with Ada.Text_IO.Text_Streams;
with DOM.Core.Documents;
with DOM.Core.Nodes;

procedure Serialization is
My_Implementation : DOM.Core.DOM_Implementation;
My_Document : DOM.Core.Document;
My_Root_Node : DOM.Core.Element;
My_Element_Node : DOM.Core.Element;
My_Text_Node : DOM.Core.Text;
begin
My_Document := DOM.Core.Create_Document (My_Implementation);
My_Root_Node := DOM.Core.Documents.Create_Element (My_Document, "root");
My_Root_Node := DOM.Core.Nodes.Append_Child (My_Document, My_Root_Node);
My_Element_Node := DOM.Core.Documents.Create_Element (My_Document, "element");
My_Element_Node := DOM.Core.Nodes.Append_Child (My_Root_Node, My_Element_Node);
My_Text_Node := DOM.Core.Documents.Create_Text_Node (My_Document, "Some text here");
My_Text_Node := DOM.Core.Nodes.Append_Child (My_Element_Node, My_Text_Node);
DOM.Core.Nodes.Write
(Stream => Ada.Text_IO.Text_Streams.Stream
(Ada.Text_IO.Standard_Output),
N => My_Document,
Pretty_Print => True);
end Serialization;</syntaxhighlight>

It can be shortened a lot by adding "use" clauses and writing the creation functions into the declaration part.

Output:
<pre><?xml version="1.0" encoding="utf-8"?>
<root>
<element>Some text here</element>
</root></pre>

=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program createXml.s */
/* install package libxml++2.6-dev */
/* link with gcc option -lxml2 */

/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall

/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndpgm: .asciz "Normal end of program.\n"
szFileName: .asciz "file1.xml"
szFileMode: .asciz "w"
szMessError: .asciz "Error detected !!!!. \n"

szVersDoc: .asciz "1.0"
szLibRoot: .asciz "root"
szLibElement: .asciz "element"
szText: .asciz "some text here"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4

/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszVersDoc
bl xmlNewDoc @ create doc
mov r9,r0 @ doc address
mov r0,#0
ldr r1,iAdrszLibRoot
bl xmlNewNode @ create root node
mov r8,r0 @ node root address
mov r0,r9
mov r1,r8
bl xmlDocSetRootElement
@TODO voir la gestion des erreurs

mov r0,#0
ldr r1,iAdrszLibElement
bl xmlNewNode @ create element node
mov r7,r0 @ node element address
ldr r0,iAdrszText
bl xmlNewText @ create text
mov r6,r0 @ text address
mov r0,r7 @ node element address
mov r1,r6 @ text address
bl xmlAddChild @ add text to element node
mov r0,r8 @ node root address
mov r1,r7 @ node element address
bl xmlAddChild @ add node elemeny to root node
ldr r0,iAdrszFileName
ldr r1,iAdrszFileMode
bl fopen @ file open
cmp r0,#0
blt 99f
mov r5,r0 @ File descriptor
mov r1,r9 @ doc
mov r2,r8 @ root
bl xmlElemDump @ write xml file
cmp r0,#0
blt 99f
mov r0,r5
bl fclose @ file close
mov r0,r9
bl xmlFreeDoc
bl xmlCleanupParser
ldr r0,iAdrszMessEndpgm
bl affichageMess
b 100f
99:
@ error
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call

iAdrszMessError: .int szMessError
iAdrszMessEndpgm: .int szMessEndpgm
iAdrszVersDoc: .int szVersDoc
iAdrszLibRoot: .int szLibRoot
iAdrszLibElement: .int szLibElement
iAdrszText: .int szText
iAdrszFileName: .int szFileName
iAdrszFileMode: .int szFileMode
iAdrszCarriageReturn: .int szCarriageReturn

/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ previous position
bne 1b @ else loop
@ end replaces digit in front of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4] @ store in area begin
add r4,#1
add r2,#1 @ previous position
cmp r2,#LGZONECAL @ end
ble 2b @ loop
mov r1,#' '
3:
strb r1,[r3,r4]
add r4,#1
cmp r4,#LGZONECAL @ end
ble 3b
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} @ save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 @ r2 <- r2 >> 2
mov r1, r0, LSR #31 @ r1 <- r0 >> 31
add r0, r2, r1 @ r0 <- r2 + r1
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2-r4}
bx lr @ return
</syntaxhighlight>

=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">version = "1.0"
xmlheader := "<?xml version=" . version . "?>" . "<" . root . ">"

element("root", "child")
element("root", "element", "more text here")
element("root_child", "kid", "yak yak")
MsgBox % xmlheader . serialize("root")
Return

element(parent, name, text="")
{
Global
%parent%_children .= name . "`n"
%parent%_%name% = %parent%_%name%
%parent%_%name%_name := name
%parent%_%name%_text := text
}

serialize(root){
StringSplit, root, root, _
xml .= "<" . root%root0% . ">"
StringTrimRight, %root%_children, %root%_children, 1
Loop, Parse, %root%_children, `n
{
If %root%_%A_LoopField%_children
xml .= serialize(%root%_%A_LoopField%)
Else
{
element := "<" . %root%_%A_LoopField%_name . ">"
element .= %root%_%A_LoopField%_text
element .= "</" . %root%_%A_LoopField%_name . ">"
xml .= element
}
}
Return xml .= "</" . root%root0% . ">"
}</syntaxhighlight>

=={{header|Bracmat}}==
To produce the XML including all indentations, we can do this:
<syntaxhighlight lang="bracmat">( ("?"."xml version=\"1.0\" ")
\n
(root.,"\n " (element.,"
Some text here
") \n)
: ?xml
& out$(toML$!xml)
);</syntaxhighlight>
If we do not care about indentation:
<syntaxhighlight lang="bracmat">( ("?"."xml version=\"1.0\"") (root.,(element.,"Some text here"))
: ?xml
& out$(toML$!xml)
);</syntaxhighlight>

=={{header|C}}==
==={{libheader|LibXML}}===
<syntaxhighlight lang="c">#include <libxml/parser.h>
#include <libxml/tree.h>
int main()
{
xmlDoc *doc = xmlNewDoc("1.0");
xmlNode *root = xmlNewNode(NULL, BAD_CAST "root");
xmlDocSetRootElement(doc, root);

xmlNode *node = xmlNewNode(NULL, BAD_CAST "element");
xmlAddChild(node, xmlNewText(BAD_CAST "some text here"));
xmlAddChild(root, node);

xmlSaveFile("myfile.xml", doc);
xmlFreeDoc(doc);
xmlCleanupParser();
}</syntaxhighlight>

==={{libheader|Gadget}}===
<p>Version 1 (48 allocs):</p>
<syntaxhighlight lang="c">
#include <gadget/gadget.h>

LIB_GADGET_START

Main
String XML, body;
Stack{
Store ( XML, Parser( "element", "","Some text here", NORMAL_TAG) );
Store ( XML, Parser( "root", "",XML, NORMAL_TAG) );
} Stack_off;
body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
Print "%s\n", body;
Free secure XML, body;
End
</syntaxhighlight>
<p>Version 2 (46 allocs):</p>
<syntaxhighlight lang="c">
#include <gadget/gadget.h>

LIB_GADGET_START

Main
String XML, body;
Get_fn_let( XML, Parser( "element", "","Some text here", NORMAL_TAG) );
Get_fn_let( XML, Parser( "root", "",XML, NORMAL_TAG) );
body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
Print "%s\n", body;
Free secure XML, body;
End
</syntaxhighlight>
<p>Version 3 (47 allocs):</p>
<syntaxhighlight lang="c">
#include <gadget/gadget.h>

LIB_GADGET_START

Main
String XML, body;
Stack{
Store ( XML, Parser( "root", "",
Parser( "element", "","Some text here", NORMAL_TAG),
NORMAL_TAG) );
} Stack_off;
body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
Print "%s\n", body;
Free secure XML, body;
End
</syntaxhighlight>

<p>Version 4 (50 allocs):</p>
<syntaxhighlight lang="c">
#include <gadget/gadget.h>

LIB_GADGET_START

Main
String body;
Stack{
Store ( body, Multi_copy( body,"<?xml version=\"1.0\" ?>",
Parser( "root", "", Parser( "element", "","Some text here",
NORMAL_TAG), NORMAL_TAG),
NULL) );
}

Print "%s\n", body;
Free secure body;
End
</syntaxhighlight>
{{out}}
<pre>
$ ./tests/RC_dom
<?xml version="1.0" ?><root><element>Some text here</element></root>
</pre>

=={{header|C sharp}}==
Serialization using the built-in System.Xml.Serialization library of .Net.
<syntaxhighlight lang="csharp">using System.Xml;
using System.Xml.Serialization;
[XmlRoot("root")]
public class ExampleXML
{
[XmlElement("element")]
public string element = "Some text here";
static void Main(string[] args)
{
var xmlnamespace = new XmlSerializerNamespaces();
xmlnamespace.Add("", ""); //used to stop default namespaces from printing
var writer = XmlWriter.Create("output.xml");
new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace);
}
//Output: <?xml version="1.0" encoding="utf-8"?><root><element>Some text here</element></root>
}</syntaxhighlight>

=={{header|C++}}==
{{libheader|LibXML}}
<syntaxhighlight lang="cpp">
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlsave.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>

#ifndef LIBXML_TREE_ENABLED
# error libxml was not configured with DOM tree support
#endif

#ifndef LIBXML_OUTPUT_ENABLED
# error libxml was not configured with serialization support
#endif

// Because libxml2 is a C library, we need a couple things to make it work
// well with modern C++:
// 1) a ScopeGuard-like type to handle cleanup functions; and
// 2) an exception type that transforms the library's errors.

// ScopeGuard-like type to handle C library cleanup functions.
template <typename F>
class [[nodiscard]] scope_exit
{
public:
// C++20: Constructor can (and should) be [[nodiscard]].
/*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :
f_{std::move(f)}
{}

~scope_exit()
{
f_();
}

// Non-copyable, non-movable.
scope_exit(scope_exit const&) = delete;
scope_exit(scope_exit&&) = delete;
auto operator=(scope_exit const&) -> scope_exit& = delete;
auto operator=(scope_exit&&) -> scope_exit& = delete;

private:
F f_;
};

// Exception that gets last libxml2 error.
class libxml_error : public std::runtime_error
{
public:
libxml_error() : libxml_error(std::string{}) {}

explicit libxml_error(std::string message) :
std::runtime_error{make_message_(std::move(message))}
{}

private:
static auto make_message_(std::string message) -> std::string
{
if (auto const last_error = ::xmlGetLastError(); last_error)
{
if (not message.empty())
message += ": ";
message += last_error->message;
}

return message;
}
};

auto add_text(::xmlNode* node, ::xmlChar const* content)
{
// Create a new text node with the desired content.
auto const text_node = ::xmlNewText(content);
if (not text_node)
throw libxml_error{"failed to create text node"};

// Try to add it to the node. If it succeeds, that node will take
// ownership of the text node. If it fails, we have to clean up the text
// node ourselves first, then we can throw.
if (auto const res = ::xmlAddChild(node, text_node); not res)
{
::xmlFreeNode(text_node);
throw libxml_error{"failed to add text node"};
}
return text_node;
}

auto main() -> int
{
// Set this to true if you don't want the XML declaration.
constexpr auto no_xml_declaration = false;

try
{
// Initialize libxml.
::xmlInitParser();
LIBXML_TEST_VERSION
auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};

// Create a new document.
auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8"1.0"));
if (not doc)
throw libxml_error{"failed to create document"};
auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};

// Create the root element.
auto root = ::xmlNewNode(nullptr,
reinterpret_cast<::xmlChar const*>(u8"root"));
if (not root)
throw libxml_error{"failed to create root element"};
::xmlDocSetRootElement(doc, root); // doc now owns root

// Add whitespace. Unless you know the whitespace is not significant,
// you should do this manually, rather than relying on automatic
// indenting.
add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n "));

// Add the child element.
if (auto const res = ::xmlNewTextChild(root, nullptr,
reinterpret_cast<::xmlChar const*>(u8"element"),
reinterpret_cast<::xmlChar const*>(
u8"\n Some text here\n "));
not res)
throw libxml_error{"failed to create child text element"};

// Add whitespace.
add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n"));

// Output tree. Note that the output is UTF-8 in all cases. If you
// want something different, use xmlSaveFileEnc() or the second
// argument of xmlSaveDoc().
if constexpr (no_xml_declaration)
{
auto const save_context = ::xmlSaveToFilename("-", nullptr,
XML_SAVE_NO_DECL);
auto const save_context_cleanup = scope_exit{[save_context] {
::xmlSaveClose(save_context); }};

if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)
throw libxml_error{"failed to write tree to stdout"};
}
else
{
if (auto const res = ::xmlSaveFile("-", doc); res == -1)
throw libxml_error{"failed to write tree to stdout"};
}
}
catch (std::exception const& x)
{
std::cerr << "ERROR: " << x.what() << '\n';
return EXIT_FAILURE;
}
}
</syntaxhighlight>

=={{header|Caché ObjectScript}}==

<pre>
USER>set writer=##class(%XML.Writer).%New()
USER>set writer.Charset="UTF-8"
USER>Set writer.Indent=1
USER>Set writer.IndentChars=" "
USER>set sc=writer.OutputToString()
USER>set sc=writer.RootElement("root")
USER>set sc=writer.Element("element")
USER>set sc=writer.WriteChars("Some text here")
USER>set sc=writer.EndElement()
USER>set sc=writer.EndRootElement()
USER>Write writer.GetXMLString()

<?xml version="1.0" encoding="UTF-8"?>
<root>
<element>Some text here</element>
</root>
</pre>

=={{header|Clojure}}==
{{libheader|clojure.data.xml}}

<syntaxhighlight lang="clojure">
(require '[clojure.data.xml :as xml])

(def xml-example (xml/element :root {} (xml/element :element {} "Some text here")))

(with-open [out-file (java.io.OutputStreamWriter.
(java.io.FileOutputStream. "/tmp/output.xml") "UTF-8")]
(xml/emit xml-example out-file))
</syntaxhighlight>

{{out}}
<pre><?xml version="1.0" encoding="UTF-8"?><root><element>Some text here</element></root></pre>

=={{header|Common Lisp}}==

{{libheader|Closure XML}}

Assuming that matching the whitespace in the problem description isn't necessary and that character encodings are permitted (see the [[Talk:DOM XML Serialization|talk page]]):

<syntaxhighlight lang="lisp">(let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil))
(root (dom:create-element doc "root"))
(element (dom:create-element doc "element"))
(text (dom:create-text-node doc "Some text here")))
(dom:append-child element text)
(dom:append-child root element)
(dom:append-child doc root)
(dom:map-document (cxml:make-rod-sink) doc))</syntaxhighlight>

gives the following output:

<pre><?xml version="1.0" encoding="UTF-8"?>
<root><element>Some text here</element></root></pre>

Because <code>dom:append-child</code> returns the appended child, the same output can be produced while binding fewer variables:

<syntaxhighlight lang="lisp">(let ((doc (dom:create-document 'rune-dom:implementation nil nil nil)))
(dom:append-child
(dom:append-child
(dom:append-child doc (dom:create-element doc "root"))
(dom:create-element doc "element"))
(dom:create-text-node doc "Some text here"))
(write-string (dom:map-document (cxml:make-rod-sink) doc)))</syntaxhighlight>

The prefix notation makes this hard to decipher, however, and so a final version uses an auxiliary <code>append-child*</code>:

<syntaxhighlight lang="lisp">(defun append-child* (parent &rest children)
(reduce 'dom:append-child children :initial-value parent))

(let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil)))
(append-child* doc
(dom:create-element doc "root")
(dom:create-element doc "element")
(dom:create-text-node doc "Some text here"))
(write-string (dom:map-document (cxml:make-rod-sink) doc)))</syntaxhighlight>

=={{header|D}}==
{{works with|D|2.011+}}
<syntaxhighlight lang="d">module xmltest ;

import std.stdio ;
import std.xml ;

void main() {
auto doc = new Document("root") ;
//doc.prolog = q"/<?xml version="1.0"?>/" ; // default
doc ~= new Element("element", "Some text here") ;
writefln(doc) ;
// output: <?xml version="1.0"?><root><element>Some text here</element></root>
}</syntaxhighlight>

=={{header|E}}==
{{works with|E-on-Java}}
This makes use of XML libraries provided with Java.

<syntaxhighlight lang="e">def document := <unsafe:javax.xml.parsers.makeDocumentBuilderFactory> \
.newInstance() \
.newDocumentBuilder() \
.getDOMImplementation() \
.createDocument(null, "root", null)
def root := document.getDocumentElement()
root.appendChild(
def element := document.createElement("element"))
element.appendChild(
document.createTextNode("Some text here"))
println(document.saveXML(root))</syntaxhighlight>

(On the use of <tt>&lt;unsafe></tt>: The class has not yet been reviewed for E safety, so <tt>&lt;import:...makeDocumentBuilderFactory></tt> is not yet allowed. The review would probably be straightforward.)

=={{header|FreeBASIC}}==
{{libheader|libxml2}}
<syntaxhighlight lang="vbnet">#include once "crt/stdio.bi"
#include once "crt/stdlib.bi"
#include once "libxml/tree.bi"
#include once "libxml/parser.bi"

'' Create a new document
Dim As xmlDocPtr doc = xmlNewDoc(Strptr("1.0"))

'' Create a root node
Dim As xmlNodePtr root_node = xmlNewNode(NULL, Strptr("root"))

'' Set the root node for the document
xmlDocSetRootElement(doc, root_node)

'' Create a new node
Dim As xmlNodePtr node = xmlNewNode(NULL, Strptr("element"))

'' Add some text to the node
xmlNodeSetContent(node, Strptr("Some text here"))

'' Add the new node to the root node
xmlAddChild(root_node, node)

'' Dump the document to stdout, it will be well formatted
xmlDocDump(stdout, doc)

'' Free the document
xmlFreeDoc(doc)

'' Free the global variables that may have been allocated by the parser
xmlCleanupParser()</syntaxhighlight>

=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System.Xml

[<EntryPoint>]
let main argv =
let xd = new XmlDocument()
// Create the required nodes:
xd.AppendChild (xd.CreateXmlDeclaration("1.0", null, null)) |> ignore
let root = xd.AppendChild (xd.CreateNode("element", "root", ""))
let element = root.AppendChild (xd.CreateElement("element", "element", ""))
element.AppendChild (xd.CreateTextNode("Some text here")) |> ignore
// The same can be accomplished with:
// xd.LoadXml("""<?xml version="1.0"?><root><element>Some text here</element></root>""")

let xw = new XmlTextWriter(System.Console.Out)
xw.Formatting <- Formatting.Indented
xd.WriteContentTo(xw)
0</syntaxhighlight>
Output
<pre><?xml version="1.0"?>
<root>
<element>Some text here</element>
</root></pre>

=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: xml.syntax xml.writer ;

<XML <root><element>Some text here</element></root> XML>
pprint-xml</syntaxhighlight>
{{out}}
<pre>
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element>
Some text here
</element>
</root>
</pre>

Factor's XML syntax isn't just for parsing static XML. Since it supports interpolation (denoted by <code><-></code>) and plays nicely with sequences, it is easy to build up arbitrary trees:
<syntaxhighlight lang="factor">USING: sequences xml.syntax xml.writer ;

3 [XML <element>Some text here</element> XML] <repetition>
[XML <element2><element3>1.0</element3></element2> XML] append
<XML <root><-></root> XML>
pprint-xml</syntaxhighlight>
{{out}}
<pre style="height:60ex">
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element>
Some text here
</element>
<element>
Some text here
</element>
<element>
Some text here
</element>
<element2>
<element3>
1.0
</element3>
</element2>
</root>
</pre>

=={{header|Fantom}}==

<syntaxhighlight lang="fantom">
using xml
class XmlDom
{
public static Void main ()
{
doc := XDoc()
root := XElem("root")
doc.add (root)
child := XElem("element")
child.add(XText("Some text here"))
root.add (child)
doc.write(Env.cur.out)
}
}
</syntaxhighlight>

Output:
<pre>
<?xml version='1.0' encoding='UTF-8'?>
<root>
<element>Some text here</element>
</root>
</pre>

=={{header|Forth}}==
{{libheader|Forth Foundation Library}}
<syntaxhighlight lang="forth">include ffl/dom.fs

\ Create a dom variable 'doc' in the dictionary

dom-create doc

\ Add the document root with its version attribute

dom.document doc dom-append-node

s" version" s" 1.0" dom.attribute doc dom-append-node

\ Add root and element

doc dom-parent 2drop

s" root" dom.element doc dom-append-node

s" element" dom.element doc dom-append-node

\ Add the text

s" Some text here" dom.text doc dom-append-node

\ Convert the document to a string and print

doc dom-write-string [IF]
type cr
[THEN]</syntaxhighlight>

=={{header|Go}}==
{{libheader|gitlab.com/stone.code/xmldom-go.git}}
A very small, subset of the W3C DOM Core in Go. The work builds off the existing XML parser. A fork of the godom project (http://code.google.com/p/godom/), which appears to be unsupported at the moment.

<syntaxhighlight lang="go">package main

import (
"fmt"
dom "gitlab.com/stone.code/xmldom-go.git"
)

func main() {
d, err := dom.ParseStringXml(`
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>`)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(d.ToXml()))
}</syntaxhighlight>
{{out}}
<syntaxhighlight lang="xml"><root>
<element>
Some text here
</element>
</root></syntaxhighlight>

=={{header|Groovy}}==
<syntaxhighlight lang="groovy">import groovy.xml.MarkupBuilder
def writer = new StringWriter() << '<?xml version="1.0" ?>\n'
def xml = new MarkupBuilder(writer)
xml.root() {
element('Some text here' )
}
println writer</syntaxhighlight>

=={{header|Haskell}}==

Using the XML.Light module from [http://hackage.haskell.org/package/xml-1.3.4 HackageDB]

<syntaxhighlight lang="haskell">import Data.List
import Text.XML.Light

xmlDOM :: String -> String
xmlDOM txt = showTopElement $ Element
(unqual "root")
[]
[ Elem $ Element
(unqual "element")
[]
[Text $ CData CDataText txt Nothing]
Nothing
]
Nothing</syntaxhighlight>
Output:
<pre>*Main> mapM_ (putStrLn.ppContent) $ parseXML (xmlDOM " Some text ")
<?xml version="1.0" ?>
<root>
<element> Some text </element>
</root></pre>

=={{header|J}}==
There are probably better ways of doing this, but, here is a simple serializer for a rudimentary concept of a dom:

<syntaxhighlight lang="j">serialize=: ('<?xml version="1.0" ?>',LF),;@serialize1&''
serialize1=:4 :0
if.L.x do.
start=. y,'<',(0{::x),'>',LF
middle=. ;;(}.x) serialize1&.> <' ',y
end=. y,'</',(0{::x),'>',LF
<start,middle,end
else.
<y,x,LF
end.
)</syntaxhighlight>

And here is a document object that matches this task:

<syntaxhighlight lang="j">obj=: 'root';<'element';'some text here'</syntaxhighlight>

Example use:

<syntaxhighlight lang="xml"> serialize obj
<?xml version="1.0" ?>
<root>
<element>
some text here
</element>
</root></syntaxhighlight>

=={{header|Java}}==
[[Java|Java's]] XML DOM tools don't really allow total control of the output format "out of the box" but the following program generates XML that is equivalent to the required output.
<syntaxhighlight lang="java">
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class RDOMSerialization {

private Document domDoc;

public RDOMSerialization() {
return;
}

protected void buildDOMDocument() {

DocumentBuilderFactory factory;
DocumentBuilder builder;
DOMImplementation impl;
Element elmt1;
Element elmt2;

try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
impl = builder.getDOMImplementation();
domDoc = impl.createDocument(null, null, null);
elmt1 = domDoc.createElement("root");
elmt2 = domDoc.createElement("element");
elmt2.setTextContent("Some text here");

domDoc.appendChild(elmt1);
elmt1.appendChild(elmt2);
}
catch (ParserConfigurationException ex) {
ex.printStackTrace();
}

return;
}

protected void serializeXML() {

DOMSource domSrc;
Transformer txformer;
StringWriter sw;
StreamResult sr;

try {
domSrc = new DOMSource(domDoc);

txformer = TransformerFactory.newInstance().newTransformer();
txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
txformer.setOutputProperty(OutputKeys.METHOD, "xml");
txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
txformer.setOutputProperty(OutputKeys.INDENT, "yes");
txformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

sw = new StringWriter();
sr = new StreamResult(sw);

txformer.transform(domSrc, sr);

System.out.println(sw.toString());
}
catch (TransformerConfigurationException ex) {
ex.printStackTrace();
}
catch (TransformerFactoryConfigurationError ex) {
ex.printStackTrace();
}
catch (TransformerException ex) {
ex.printStackTrace();
}

return;
}

public static void serializationDriver(String[] args) {

RDOMSerialization lcl = new RDOMSerialization();
lcl.buildDOMDocument();
lcl.serializeXML();

return;
}

public static void main(String[] args) {
serializationDriver(args);
return;
}
}
</syntaxhighlight>

'''Output:'''


<syntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
'''Interpreter:''' Firefox 2.0
<root>
<element>Some text here</element>
</root></syntaxhighlight>


=={{header|JavaScript}}==
{{works with|Firefox|2.0}}
DOM
DOM


var doc = document.implementation.createDocument( null, 'root', null );
<syntaxhighlight lang="javascript">var doc = document.implementation.createDocument( null, 'root', null );
var root = doc.documentElement;
var root = doc.documentElement;
var element = doc.createElement( 'element' );
var element = doc.createElement( 'element' );
root.appendChild( element );
root.appendChild( element );
element.appendChild( document.createTextNode('Some text here') );
element.appendChild( document.createTextNode('Some text here') );
var xmlString = new XMLSerializer().serializeToString( doc );
var xmlString = new XMLSerializer().serializeToString( doc );</syntaxhighlight>


E4X
E4X


var xml = <root>
<syntaxhighlight lang="javascript">var xml = <root>
<element>Some text here</element>
<element>Some text here</element>
</root>;
</root>;
var xmlString = xml.toXMLString();
var xmlString = xml.toXMLString();</syntaxhighlight>


E4X — with processing instruction
E4X — with processing instruction


XML.ignoreProcessingInstructions = false;
<syntaxhighlight lang="javascript">XML.ignoreProcessingInstructions = false;
var xml = <?xml version="1.0"?>
var xml = <?xml version="1.0"?>
<root>
<root>
<element>Some text here</element>
</root>;
var xmlString = xml.toXMLString();</syntaxhighlight>

=={{header|Julia}}==
<syntaxhighlight lang="julia">using LightXML

# Modified from the documentation for LightXML.jl. The underlying library requires an encoding string be printed.

# create an empty XML document
xdoc = XMLDocument()

# create & attach a root node
xroot = create_root(xdoc, "root")

# create the first child
xs1 = new_child(xroot, "element")

# add the inner content
add_text(xs1, "some text here")

println(xdoc)

</syntaxhighlight>{{output}}<pre>
<?xml version="1.0" encoding="utf-8"?>
<root>
<element>some text here</element>
</root>
</pre>

=={{header|Kotlin}}==
This is the closest I could get to the required output.

There appears to be no satisfactory way to prevent the default encoding and standalone attributes from appearing in the XML declaration using the standard JDK DOM implementation. If you set the standalone attribute to true - using doc.setXmlStandalone(true) - then this removes it from the declaration but unfortunately there is then no carriage return before the <root> tag!

So I've decided to leave it as it is.
<syntaxhighlight lang="scala">// 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 dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
val doc = dBuilder.newDocument()
val root = doc.createElement("root") // create root node
doc.appendChild(root)
val element = doc.createElement("element") // create element node
val text = doc.createTextNode("Some text here") // create text node
element.appendChild(text)
root.appendChild(element)

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

{{out}}
<pre>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<element>Some text here</element>
<element>Some text here</element>
</root>;
</root>
</pre>
var xmlString = xml.toXMLString();


=={{header|Lasso}}==
==[[Perl]]==
<syntaxhighlight lang="lasso">
[[Category:Perl]]
content_type( 'text/xml' );// set MIME type if serving
use XML::DOM::BagOfTricks qw(createDocument createTextElement);
my ($doc, $root) = createDocument('root');
$root->appendChild(
createTextElement($doc, 'element', 'Some text here')
);
print $doc->toString;


xml( '<?xml version="1.0" ?><root><element>Some text here</element></root>' );
==[[PHP]]==
[[Category:PHP]]


</syntaxhighlight>
'''Interpreter:''' [[PHP]] 5


=={{header|Lingo}}==
<?php
Code based on Flash Xtra (comes with Director, i.e. "built-in") that allows to use AS2/AS3 classes in Lingo (in this case "XML" is an AS2 class).
$dom = new DOMDocument();//the constructor also takes the version and char-encoding as it's two respective parameters
<syntaxhighlight lang="lingo">-- create an XML document
$dom->formatOutput = true;//format the outputted xml
doc = newObject("XML", "<?xml version='1.0' ?>")
$root = $dom->createElement('root');
$element = $dom->createElement('element');
$element->appendChild($dom->createTextNode('Some text here'));
$root->appendChild($element);
$dom->appendChild($root);
$xmlstring = $dom->saveXML();


root = doc.createElement("root")
==[[Python]]==
doc.appendChild(root)
[[Category:Python]]


element = doc.createElement("element")
'''Interpreter:''' [[Python]] 2.5
root.appendChild(element)


textNode = doc.createTextNode("Some text here")
from xml.dom.minidom import getDOMImplementation
element.appendChild(textNode)

put doc.toString()
-- "<?xml version='1.0' ?><root><element>Some text here</element></root>"</syntaxhighlight>

=={{header|Lua}}==
Using the widely available 'LuaXML' module
<syntaxhighlight lang="lua">require("LuaXML")
local dom = xml.new("root")
local element = xml.new("element")
table.insert(element, "Some text here")
dom:append(element)
dom:save("dom.xml")</syntaxhighlight>
Resulting contents of dom.xml:
<pre><?xml version="1.0"?>
<!-- file "dom.xml", generated by LuaXML -->

<root>
<element>Some text here</element>
</root></pre>

=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">DOM = XMLObject["Document"][{XMLObject["Declaration"]["Version" -> "1.0","Encoding" -> "utf-8"]},
XMLElement["root", {}, {XMLElement["element", {}, {"Some text here"}]}], {}];
ExportString[DOM, "XML", "AttributeQuoting" -> "\""]</syntaxhighlight>
{{out}}
<pre><?xml version="1.0" encoding="utf-8"?>
<root>
<element>Some text here</element>
</root></pre>

=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">docNode = com.mathworks.xml.XMLUtils.createDocument('root');
docRootNode = docNode.getDocumentElement;
thisElement = docNode.createElement('element');
thisElement.appendChild(docNode.createTextNode('Some text here'));
docRootNode.appendChild(thisElement);
</syntaxhighlight>
Output:
<pre> xmlwrite(docNode)

ans =

<?xml version="1.0" encoding="utf-8"?>
<root>
<element>Some text here</element>
</root>
</pre>

=={{header|NetRexx}}==
{{trans|Java}}
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary

import java.io.StringWriter
import javax.xml.
import org.w3c.dom.

class RDOMSerialization public

properties private
domDoc = Document

method main(args = String[]) public static

lcl = RDOMSerialization()
lcl.buildDOMDocument()
lcl.serializeXML()

return

method buildDOMDocument() inheritable

do
factory = DocumentBuilderFactory.newInstance()
builder = factory.newDocumentBuilder()
impl = builder.getDOMImplementation()
domDoc = impl.createDocument(null, null, null)
elmt1 = domDoc.createElement("root")
elmt2 = domDoc.createElement("element")
elmt2.setTextContent("Some text here")

domDoc.appendChild(elmt1)
elmt1.appendChild(elmt2)
catch exPC = ParserConfigurationException
dom = getDOMImplementation()
exPC.printStackTrace
document = dom.createDocument(None, "root", None)
end
return
topElement = document.documentElement

firstElement = document.createElement("element")
method serializeXML() inheritable
topElement.appendChild(firstElement)

textNode = document.createTextNode("Some text here")
do
firstElement.appendChild(textNode)
domSrc = DOMSource(domDoc)
txformer = TransformerFactory.newInstance().newTransformer()
txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no")
txformer.setOutputProperty(OutputKeys.METHOD, "xml")
txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")
txformer.setOutputProperty(OutputKeys.INDENT, "yes")
txformer.setOutputProperty(OutputKeys.STANDALONE, "yes")
txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
sw = StringWriter()
sr = StreamResult(sw)
txformer.transform(domSrc, sr)
say sw.toString
xmlString = document.toprettyxml(" " * 4)


catch exTC = TransformerConfigurationException
exTC.printStackTrace
catch exTF = TransformerFactoryConfigurationError
exTF.printStackTrace
catch exTE = TransformerException
exTE.printStackTrace
end


return
'''Interpreter:''' [[Python]] 2.5
</syntaxhighlight>


'''Output:'''
from xml.etree import ElementTree as et

<syntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8" standalone="no"?>
root = et.Element("root")
<root>
et.SubElement(root, "element").text = "Some text here"
<element>Some text here</element>
xmlString = et.tostring(root)
</root></syntaxhighlight>

=={{header|Nim}}==
{{libheader|nim-xmldom}}
Note that the module “xmldom” is no longer part of the standard library as more convenient modules are now available. It can be installed using the package manager <code>nimble</code>.
<syntaxhighlight lang="nim">import xmldom

var
dom = getDOM()
document = dom.createDocument("", "root")
topElement = document.documentElement
firstElement = document.createElement "element"
textNode = document.createTextNode "Some text here"

topElement.appendChild firstElement
firstElement.appendChild textNode

echo document</syntaxhighlight>
Output:
<pre><?xml version="1.0" encoding="UTF-8" ?>
<root>
<element>
Some text here
</element>
</root></pre>

=={{header|Objeck}}==
<syntaxhighlight lang="objeck">use XML;

bundle Default {
class Test {
function : Main(args : String[]) ~ Nil {
builder := XMLBuilder->New("root", "1.0");
root := builder->GetRoot();
element := XMLElement->New(XMLElementType->ELEMENT, "element", "Some text here");
root->AddChild(element);
builder->ToString()->PrintLine();
}
}
}</syntaxhighlight>

=={{header|OpenEdge/Progress}}==
The following example uses the X-DOCUMENT, for faster processing SAX can be used.
<syntaxhighlight lang="progress">
DEFINE VARIABLE hxdoc AS HANDLE NO-UNDO.
DEFINE VARIABLE hxroot AS HANDLE NO-UNDO.
DEFINE VARIABLE hxelement AS HANDLE NO-UNDO.
DEFINE VARIABLE hxtext AS HANDLE NO-UNDO.
DEFINE VARIABLE lcc AS LONGCHAR NO-UNDO.

CREATE X-DOCUMENT hxdoc.

CREATE X-NODEREF hxroot.
hxdoc:CREATE-NODE( hxroot, 'root', 'ELEMENT' ).
hxdoc:APPEND-CHILD( hxroot ).

CREATE X-NODEREF hxelement.
hxdoc:CREATE-NODE( hxelement, 'element', 'ELEMENT' ).
hxroot:APPEND-CHILD( hxelement ).

CREATE X-NODEREF hxtext.
hxdoc:CREATE-NODE( hxtext, 'element', 'TEXT' ).
hxelement:APPEND-CHILD( hxtext ).
hxtext:NODE-VALUE = 'Some text here'.

hxdoc:SAVE( 'LONGCHAR', lcc ).
MESSAGE STRING( lcc ) VIEW-AS ALERT-BOX.
</syntaxhighlight>

=={{header|Oz}}==
With the code from [[XML Creation#Oz]], we can write:

<syntaxhighlight lang="oz">declare
proc {Main}
DOM = root(element("Some text here"))
in
{System.showInfo {Serialize DOM}}
end
...</syntaxhighlight>

Output:
<syntaxhighlight lang="xml"><?xml version="1.0" ?>
<root>
<element>Some text here</element>
</root></syntaxhighlight>

=={{header|Pascal}}==
{{works with|Free_Pascal}} {{libheader|Classes}} {{libheader|XMLWrite}} {{libheader|DOM}}
<syntaxhighlight lang="pascal">program CrearXML;

{$mode objfpc}{$H+}

uses
Classes, XMLWrite, DOM;

var
xdoc: TXMLDocument; // variable objeto documento XML
NodoRaiz, NodoPadre, NodoHijo: TDOMNode; // variables a los nodos
begin
//crear el documento
xdoc := TXMLDocument.create;

NodoRaiz := xdoc.CreateElement('root'); // crear el nodo raíz
Xdoc.Appendchild(NodoRaiz); // guardar nodo raíz
NodoPadre := xdoc.CreateElement('element'); // crear el nodo hijo
NodoHijo := xdoc.CreateTextNode('Some text here'); // insertar el valor del nodo
NodoPadre.Appendchild(NodoHijo); // guardar nodo
NodoRaiz.AppendChild(NodoPadre); // insertar el nodo hijo en el correspondiente nodo padre
writeXMLFile(xDoc,'prueba.xml'); // escribir el XML
NodoRaiz.free;
NodoPadre.free;
NodoHijo.free;
Xdoc.free;
end.</syntaxhighlight>

Output:<pre>
<?xml version="1.0"?>
<root>
<element>Some text here</element>
</root>.
</pre>

=={{header|Perl}}==

{{libheader|XML::Simple}}
<syntaxhighlight lang="perl">use XML::Simple;
print XMLout( { root => { element => "Some text here" } }, NoAttr => 1, RootName => "" );</syntaxhighlight>

'''Output''':
<root>
<element>Some text here</element>
</root>

{{libheader|XML::DOM::BagOfTricks}}
<syntaxhighlight lang="perl">use XML::DOM::BagOfTricks qw(createDocument createTextElement);

my ($doc, $root) = createDocument('root');
$root->appendChild(
createTextElement($doc, 'element', 'Some text here')
);
print $doc->toString;</syntaxhighlight>

'''Output''':
<root><element>Some text here</element></root>

{{libheader|LibXML}}
<syntaxhighlight lang="perl">use XML::LibXML;

$xml = XML::LibXML::Document->new('1.0');
$node = $xml->createElement('root');
$xml->setDocumentElement($node);
$node2 = $xml->createElement('element');
$text = $xml->createTextNode('Some text here');
$node2->addChild($text);
$node->appendWellBalancedChunk('text');
$node->addChild($node2);

print $xml->toString;</syntaxhighlight>

'''Output''':
<?xml version="1.0"?>
<root>text<element>Some text here</element></root>

=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">xml</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">elem</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xml_new_element</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"element"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Some text here"</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">root</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xml_new_element</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"root"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">elem</span><span style="color: #0000FF;">}),</span>
<span style="color: #000000;">doc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xml_new_doc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">root</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">`&lt;?xml version="1.0" ?&gt;`</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">xml_sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">doc</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
<?xml version="1.0" ?>
<root>
<element>Some text here</element>
</root>
</pre>
If only one parameter is supplied to xml_new_doc(), the output includes the default `encoding="utf-8" `.

=={{header|PHP}}==
{{works with|PHP|5}}
<syntaxhighlight lang="php"><?php
$dom = new DOMDocument();//the constructor also takes the version and char-encoding as it's two respective parameters
$dom->formatOutput = true;//format the outputted xml
$root = $dom->createElement('root');
$element = $dom->createElement('element');
$element->appendChild($dom->createTextNode('Some text here'));
$root->appendChild($element);
$dom->appendChild($root);
$xmlstring = $dom->saveXML();</syntaxhighlight>

=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(load "@lib/xm.l")

(xml? T)
(xml '(root NIL (element NIL "Some text here")))</syntaxhighlight>
Output:
<pre><?xml version="1.0" encoding="utf-8"?>
<root>
<element>Some text here</element>
</root></pre>

=={{header|Pike}}==
manually, one node at a time:
<syntaxhighlight lang="pike">object dom = Parser.XML.Tree.SimpleRootNode();
dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), ""));
object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "root", ([]), "");
dom->add_child(node);

object subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "element", ([]), "");
node->add_child(subnode);

node = subnode;
subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "Some text here");
node->add_child(subnode);

dom->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?><root><element>Some text here</element></root>"</syntaxhighlight>

from an array, using a conversion function:
<syntaxhighlight lang="pike">object make_xml_node(array|string in, void|int level)
{
level++;
if (stringp(in))
return Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), in);
else
{
object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, in[0], in[1], "");
foreach(in[2..];; array|string child)
{
node->add_child(make_xml_node(child, level));
}
return node;
}
}

object make_xml_tree(array input)
{
object dom = Parser.XML.Tree.SimpleRootNode();
dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), ""));
dom->add_child(make_xml_node(input));
return dom;
}

array input = ({ "root", ([]), ({ "element", ([]), "Some text here" }) });
make_xml_tree(input)->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?><root><element>Some text here</element></root>"</syntaxhighlight>

to render the output with indenting as specified in the task, this function adds the necessary text nodes:
<syntaxhighlight lang="pike">object indent_xml(object parent, void|int indent_text, void|int level)
{
int subnodes = false;
foreach(parent->get_children();; object child)
{
if (child->get_node_type() == Parser.XML.Tree.XML_ELEMENT ||
(child->get_node_type() == Parser.XML.Tree.XML_TEXT && indent_text))
{
subnodes = true;
parent->add_child_before(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "\r\n"+" "*level), child);
indent_xml(child, indent_text, level+1);
}
}
if (subnodes && level)
parent->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "\r\n"+" "*(level-1)));
return parent;
}


indent_xml(make_xml_tree(input))->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?>\r\n"
"<root>\r\n"
" <element>Some text here</element>\r\n"
"</root>"

indent_xml(make_xml_tree(input), 1)->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?>\r\n"
"<root>\r\n"
" <element>\r\n"
" Some text here\r\n"
" </element>\r\n"
"</root>"</syntaxhighlight>

=={{header|Python}}==
{{works with|Python|2.5}}
<syntaxhighlight lang="python">from xml.dom.minidom import getDOMImplementation

dom = getDOMImplementation()
document = dom.createDocument(None, "root", None)

topElement = document.documentElement
firstElement = document.createElement("element")
topElement.appendChild(firstElement)
textNode = document.createTextNode("Some text here")
firstElement.appendChild(textNode)

xmlString = document.toprettyxml(" " * 4)</syntaxhighlight>

<syntaxhighlight lang="python">from xml.etree import ElementTree as et

root = et.Element("root")
et.SubElement(root, "element").text = "Some text here"
xmlString = et.tostring(root)</syntaxhighlight>

=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang at-exp racket
(require xml)

(define xml-str
@~a{<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>})

;; read & parse to get an xml value
(define xml (read-xml/document (open-input-string xml-str)))
;; print it out in xml form, which is identical to the input xml
(write-xml xml)
(newline)
</syntaxhighlight>

=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.05}}

<syntaxhighlight lang="raku" line>use XML;
use XML::Writer;

say my $document = XML::Document.new(
XML::Writer.serialize( :root[ :element['Some text here', ], ] )
);</syntaxhighlight>
{{out}}
<syntaxhighlight lang="xml"><?xml version="1.0"?><root><element>Some text here</element></root></syntaxhighlight>

=={{header|Rascal}}==
<syntaxhighlight lang="rascal">import lang::xml::DOM;

public void main(){
x = document(element(none(), "root", [element(none(), "element", [charData("Some text here")])]));
return println(xmlPretty(x));
}</syntaxhighlight>
Output example:
<syntaxhighlight lang="rascal">rascal>main()
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element>Some text here</element>
</root></syntaxhighlight>

=={{header|Ruby}}==
{{libheader|REXML}}
<syntaxhighlight lang="ruby">require("rexml/document")
include REXML
(doc = Document.new) << XMLDecl.new
root = doc.add_element('root')
element = root.add_element('element')
element.add_text('Some text here')

# save to a string
# (the first argument to write() needs an object that understands "<<")
serialized = String.new
doc.write(serialized, 4)
puts serialized</syntaxhighlight>

produces
<pre><?xml version='1.0'?>
<root>
<element>
Some text here
</element>
</root></pre>

=={{header|Scala}}==
<syntaxhighlight lang="scala">val xml = <root><element>Some text here</element></root>
scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null)</syntaxhighlight>

=={{header|Sidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">require('XML::Simple');
print %S'XML::Simple'.XMLout(
:(root => :( element => 'Some text here' )),
NoAttr => 1, RootName => '',
);</syntaxhighlight>
{{out}}
<pre>
<root>
<element>Some text here</element>
</root>
</pre>

=={{header|Tcl}}==
{{libheader|tDOM}}
<syntaxhighlight lang="tcl">package require tdom
set d [dom createDocument root]
set root [$d documentElement]
$root appendChild [$d createElement element]
[$root firstChild] appendChild [$d createTextNode "Some text here"]
$d asXML</syntaxhighlight>
<pre><root>
<element>Some text here</element>
</root></pre>
Using [http://tclxml.sf.net TclDOM]
<syntaxhighlight lang="tcl">package require dom
set doc [dom::DOMImplementation create]
set root [dom::document createElement $doc root]
set elem [dom::document createElement $root element]
set text [dom::document createTextNode $elem "Some text here"]
dom::DOMImplementation serialize $doc -newline {element}</syntaxhighlight>
<pre><?xml version='1.0'?>
<!DOCTYPE root>
<root>
<element>
Some text here
</element>
</root></pre>

=={{header|Wren}}==
Wren has no built-in or (AFAIK) third party support for XML so we code a minimal DOM sufficient for completing this task.
<syntaxhighlight lang="wren">class XmlDocument {
construct new(root) {
_root = root
}

toString { "<?xml version=\"1.0\" ?>\n%(_root.toString(0))" }
}

class XmlElement {
construct new(name, text) {
_name = name
_text = text
_children = []
}

name { _name }
text { _text }
children { _children }

addChild(child) { _children.add(child) }

toString(level) {
var indent = " "
var s = indent * level + "<%(name)>\n"
if (_text != "") s = s + indent * (level + 1) + _text + "\n"
for (c in _children) {
s = s + c.toString(level+1) + "\n"
}
return s + indent * level + "</%(name)>"
}
}

var root = XmlElement.new("root", "")
var child = XmlElement.new("element", "Some text here")
root.addChild(child)
var doc = XmlDocument.new(root)
System.print(doc)</syntaxhighlight>

{{out}}
<pre>
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
</pre>
<br>
{{libheader|Wren-xsequence}}
Since the first version was written, the above XML parser has appeared and, consequently, the solution can now be rewritten as follows.
<syntaxhighlight lang="wren">import "./xsequence" for XDocument, XElement

var doc = XDocument.new(
XElement.new("root",
XElement.new("element", "Some text here")
)
)
System.print(doc)</syntaxhighlight>
{{out}}
<pre>
<?xml version="1.0" encoding="utf-8"?>
<root>
<element>Some text here</element>
</root>
</pre>

=={{header|XProc}}==
<syntaxhighlight lang="xml"><p:pipeline xmlns:p="http://www.w3.org/ns/xproc" version="1.0">
<p:identity>
<p:input port="source">
<p:inline>
<root>
<element>
Some text here
</element>
</root>
</p:inline>
</p:input>
</p:identity>
</p:pipeline></syntaxhighlight>

=={{header|XQuery}}==
In XQuery static element construction is like normal XML:
<syntaxhighlight lang="xquery"><root>
<element>
Some text here
</element>
</root></syntaxhighlight>

Dynamic element construction looks quite different:
<syntaxhighlight lang="xquery">let $rootTagname := 'root'
let $elementTagname := 'element'
let $elementContent := 'Some text here'

return
element {$rootTagname}
{
element{$elementTagname}
{$elementContent}
}</syntaxhighlight>

=={{header|XSLT}}==
<syntaxhighlight lang="xml"><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/"> <!-- replace the root of the incoming document with our own model -->
<xsl:element name="root">
<xsl:element name="element">
<xsl:text>Some text here</xsl:text>
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet></syntaxhighlight>

=={{header|Z80 Assembly}}==
Assembled and run using WinAPE's built-in assembler. Tags have to be manually opened and closed, but it works!
<syntaxhighlight lang="z80">org &1000
main:
ld hl,XML_Header
ld de,XMLRam
call strcpy

ld hl,XML_Root
push hl
call AddXMLNode

ld hl,XML_Element
push hl
call AddXMLNode

ld hl,XML_Entry
call strcpy

pop hl ;ld hl,XML_Element
call CloseXMLNode

pop hl ;ld hl,XML_Root
call CloseXMLNode

ld hl,XMLRam
jp PrintString ;and then return to basic.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
AddXMLNode:
;hl = pointer to desired node name
;de = destination ram
;carry flag; set = <foo/>, clear = <foo></foo>
push af
ld a,'<'
ld (de),a
inc de
call strcpy
pop af
jr nc,skip_AddXMLNode
ld a,'/'
ld (de),a
inc de
skip_AddXMLNode:
ld a,'>'
ld (de),a
inc de
xor a
ld (de),a
;don't inc de afterwards, since we may want to add more
ret

CloseXMLNode:
ld a,'<'
ld (de),a
inc de
ld a,'/'
ld (de),a
inc de
call strcpy
ld a,'>'
ld (de),a
inc de
xor a
ld (de),a
ret

PrintString:
ld a,(hl)
or a
ret z
call &BB5A
inc hl
jr PrintString

strcpy:
;HL = string source
;DE = destination
;copies 1 byte at a time until a null terminator is copied, then exits.
ld a,(hl)
ld (de),a
or a
ret z
inc hl
inc de
jp strcpy

org &1200
XML_Header:
byte "<?xml version=",&22,"1.0",&22,"?>",0
XML_Root:
byte "root",0
XML_Element:
byte "element",0
XML_Entry:
byte "some text here",0

org &1300
XMLRam: ;this is where the output is stored.</syntaxhighlight>

{{out}}
<pre>call &1000
<?xml version="1.0"?><root><element>some text here</element></root></pre>


{{omit from|Batch File|No way of XML parsing or processing.}}
==[[Ruby]]==
{{omit from|GUISS}}
[[Category:Ruby]]
{{omit from|ML/I}}
require("rexml/document")
{{omit from|M4}}
include REXML
{{omit from|PARI/GP|No real capacity for string manipulation}}
(xml = Document.new) << XMLDecl.new
root=xml.add_element('root')
element=root.add_element('element')
element.add_text('Some text here')
puts xml.to_s(0)

Latest revision as of 20:22, 27 March 2024

Task
XML/DOM serialization
You are encouraged to solve this task according to the task description, using any language you may know.

Create a simple DOM and having it serialize to:

 <?xml version="1.0" ?>
 <root>
     <element>
         Some text here
     </element>
 </root>

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program createXml64.s   */
/* install package   libxml++2.6-dev    */
/* link with gcc option -I/usr/include/libxml2 -lxml2    */
 
/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessEndpgm:      .asciz "Normal end of program.\n" 
szFileName:        .asciz "file1.xml" 
szFileMode:        .asciz "w"
szMessError:       .asciz "Error detected !!!!. \n"
 
szVersDoc:         .asciz "1.0"
szLibRoot:         .asciz "root"
szLibElement:      .asciz "element"
szText:            .asciz "some text here"
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss 
.align 4
 
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                                     // entry of program 
    ldr x0,qAdrszVersDoc
    bl xmlNewDoc                          // create doc
    mov x19,x0                            // doc address
    mov x0,#0
    ldr x1,qAdrszLibRoot
    bl xmlNewNode                         // create root node
    cbz x0,99f
    mov x20,x0                            // node root address
    mov x0,x19
    mov x1,x20
    bl xmlDocSetRootElement
    mov x0,#0
    ldr x1,qAdrszLibElement
    bl xmlNewNode                         // create element node
    mov x21,x0                             // node element address
    ldr x0,qAdrszText
    bl xmlNewText                         // create text
    mov x22,x0                             // text address
    mov x0,x21                             // node element address
    mov x1,x22                             // text address
    bl xmlAddChild                        // add text to element node
    mov x0,x20                             // node root address
    mov x1,x21                             // node element address
    bl xmlAddChild                        // add node elemeny to root node
    ldr x0,qAdrszFileName
    ldr x1,qAdrszFileMode
    bl fopen                              // file open
    cmp x0,#0
    blt 99f
    mov x23,x0                             // File descriptor
    mov x1,x19                             // doc
    mov x2,x20                             // root
    bl xmlElemDump                        // write xml file
    cmp x0,#0
    blt 99f
    mov x0,x23
    bl fclose                             // file close
    mov x0,x19
    bl xmlFreeDoc
    bl xmlCleanupParser
    ldr x0,qAdrszMessEndpgm
    bl affichageMess
    b 100f
99:                                        // error
    ldr x0,qAdrszMessError
    bl affichageMess       
100:                                       // standard end of the program 
    mov x0,0                               // return code
    mov x8,EXIT                            // request to exit program
    svc 0                                  // perform the system call
 
qAdrszMessError:          .quad szMessError
qAdrszMessEndpgm:         .quad szMessEndpgm
qAdrszVersDoc:            .quad szVersDoc
qAdrszLibRoot:            .quad szLibRoot
qAdrszLibElement:         .quad szLibElement
qAdrszText:               .quad szText
qAdrszFileName:           .quad szFileName
qAdrszFileMode:           .quad szFileMode
qAdrszCarriageReturn:     .quad szCarriageReturn
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

ABAP

DATA: xml_string TYPE string.

DATA(xml)  = cl_ixml=>create( ).
DATA(doc)  = xml->create_document( ).
DATA(root) = doc->create_simple_element( name   = 'root'
                                         parent = doc ).

doc->create_simple_element( name   = 'element'
                            parent = root
                            value  = 'Some text here' ).

DATA(stream_factory) = xml->create_stream_factory( ).
DATA(stream)         = stream_factory->create_ostream_cstring( string = xml_string ).
DATA(renderer)       = xml->create_renderer( document = doc
                                             ostream  = stream ).
stream->set_pretty_print( abap_true ).
renderer->render( ).

cl_demo_output=>display_text( xml_string ).

Output:

<?xml version="1.0" encoding="utf-16"?>
<root>
<element>Some text here</element>
</root>

Ada

Works with: GNAT

Uses XML/Ada from AdaCore.

with Ada.Text_IO.Text_Streams;
with DOM.Core.Documents;
with DOM.Core.Nodes;

procedure Serialization is
   My_Implementation : DOM.Core.DOM_Implementation;
   My_Document       : DOM.Core.Document;
   My_Root_Node      : DOM.Core.Element;
   My_Element_Node   : DOM.Core.Element;
   My_Text_Node      : DOM.Core.Text;
begin
   My_Document := DOM.Core.Create_Document (My_Implementation);
   My_Root_Node := DOM.Core.Documents.Create_Element (My_Document, "root");
   My_Root_Node := DOM.Core.Nodes.Append_Child (My_Document, My_Root_Node);
   My_Element_Node := DOM.Core.Documents.Create_Element (My_Document, "element");
   My_Element_Node := DOM.Core.Nodes.Append_Child (My_Root_Node, My_Element_Node);
   My_Text_Node := DOM.Core.Documents.Create_Text_Node (My_Document, "Some text here");
   My_Text_Node := DOM.Core.Nodes.Append_Child (My_Element_Node, My_Text_Node);
   DOM.Core.Nodes.Write
     (Stream => Ada.Text_IO.Text_Streams.Stream
        (Ada.Text_IO.Standard_Output),
      N => My_Document,
      Pretty_Print => True);
end Serialization;

It can be shortened a lot by adding "use" clauses and writing the creation functions into the declaration part.

Output:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <element>Some text here</element>
</root>

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program createXml.s   */
/* install package   libxml++2.6-dev    */
/* link with gcc option -lxml2    */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessEndpgm:      .asciz "Normal end of program.\n" 
szFileName:        .asciz "file1.xml" 
szFileMode:        .asciz "w"
szMessError:       .asciz "Error detected !!!!. \n"

szVersDoc:         .asciz "1.0"
szLibRoot:         .asciz "root"
szLibElement:      .asciz "element"
szText:            .asciz "some text here"
szCarriageReturn:  .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss 
.align 4

/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                                     @ entry of program 
    ldr r0,iAdrszVersDoc
    bl xmlNewDoc                          @ create doc
    mov r9,r0                             @ doc address
    mov r0,#0
    ldr r1,iAdrszLibRoot
    bl xmlNewNode                         @ create root node
    mov r8,r0                             @ node root address
    mov r0,r9
    mov r1,r8
    bl xmlDocSetRootElement
@TODO voir la gestion des erreurs

    mov r0,#0
    ldr r1,iAdrszLibElement
    bl xmlNewNode                         @ create element node
    mov r7,r0                             @ node element address
    ldr r0,iAdrszText
    bl xmlNewText                         @ create text
    mov r6,r0                             @ text address
    mov r0,r7                             @ node element address
    mov r1,r6                             @ text address
    bl xmlAddChild                        @ add text to element node
    mov r0,r8                             @ node root address
    mov r1,r7                             @ node element address
    bl xmlAddChild                        @ add node elemeny to root node
    ldr r0,iAdrszFileName
    ldr r1,iAdrszFileMode
    bl fopen                              @ file open
    cmp r0,#0
    blt 99f
    mov r5,r0                             @ File descriptor
    mov r1,r9                             @ doc
    mov r2,r8                             @ root
    bl xmlElemDump                        @ write xml file
    cmp r0,#0
    blt 99f
    mov r0,r5
    bl fclose                             @ file close
    mov r0,r9
    bl xmlFreeDoc
    bl xmlCleanupParser
    ldr r0,iAdrszMessEndpgm
    bl affichageMess
    b 100f
99:
    @ error
    ldr r0,iAdrszMessError
    bl affichageMess       
100:                                       @ standard end of the program 
    mov r0, #0                             @ return code
    mov r7, #EXIT                          @ request to exit program
    svc #0                                 @ perform the system call

iAdrszMessError:          .int szMessError
iAdrszMessEndpgm:         .int szMessEndpgm
iAdrszVersDoc:            .int szVersDoc
iAdrszLibRoot:            .int szLibRoot
iAdrszLibElement:         .int szLibElement
iAdrszText:               .int szText
iAdrszFileName:           .int szFileName
iAdrszFileMode:           .int szFileMode
iAdrszCarriageReturn:     .int szCarriageReturn

/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                   @ save  registres
    mov r2,#0                               @ counter length 
1:                                          @ loop length calculation 
    ldrb r1,[r0,r2]                         @ read octet start position + index 
    cmp r1,#0                               @ if 0 its over 
    addne r2,r2,#1                          @ else add 1 in the length 
    bne 1b                                  @ and loop 
                                            @ so here r2 contains the length of the message 
    mov r1,r0                               @ address message in r1 
    mov r0,#STDOUT                          @ code to write to the standard output Linux 
    mov r7, #WRITE                          @ code call system "write" 
    svc #0                                  @ call systeme 
    pop {r0,r1,r2,r7,lr}                    @ restaur registers */ 
    bx lr                                   @ return  
/******************************************************************/
/*     Converting a register to a decimal                                 */ 
/******************************************************************/
/* r0 contains value and r1 address area   */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                         @ save registers 
    mov r3,r1
    mov r2,#LGZONECAL
1:                                          @ start loop
    bl divisionpar10                        @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                              @ digit
    strb r1,[r3,r2]                         @ store digit on area
    cmp r0,#0                               @ stop if quotient = 0 
    subne r2,#1                               @ previous position    
    bne 1b                                  @ else loop
                                            @ end replaces digit in front of area
    mov r4,#0
2:
    ldrb r1,[r3,r2] 
    strb r1,[r3,r4]                         @ store in area begin
    add r4,#1
    add r2,#1                               @ previous position
    cmp r2,#LGZONECAL                       @ end
    ble 2b                                  @ loop
    mov r1,#' '
3:
    strb r1,[r3,r4]
    add r4,#1
    cmp r4,#LGZONECAL                       @ end
    ble 3b
100:
    pop {r1-r4,lr}                          @ restaur registres 
    bx lr                                   @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*  
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10:
  /* r0 contains the argument to be divided by 10 */
    push {r2-r4}                           @ save registers  */
    mov r4,r0  
    mov r3,#0x6667                         @ r3 <- magic_number  lower
    movt r3,#0x6666                        @ r3 <- magic_number  upper
    smull r1, r2, r3, r0                   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) 
    mov r2, r2, ASR #2                     @ r2 <- r2 >> 2
    mov r1, r0, LSR #31                    @ r1 <- r0 >> 31
    add r0, r2, r1                         @ r0 <- r2 + r1 
    add r2,r0,r0, lsl #2                   @ r2 <- r0 * 5 
    sub r1,r4,r2, lsl #1                   @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2-r4}
    bx lr                                  @ return

AutoHotkey

version = "1.0"
xmlheader := "<?xml version=" . version . "?>" . "<" . root . ">"

element("root", "child")
element("root", "element", "more text here")
element("root_child", "kid", "yak yak")
MsgBox % xmlheader . serialize("root")
Return

element(parent, name, text="")
{
  Global
  %parent%_children .= name . "`n"
  %parent%_%name% = %parent%_%name%
  %parent%_%name%_name := name
  %parent%_%name%_text := text
}

serialize(root){
  StringSplit, root, root, _
  xml .= "<" . root%root0% . ">"
  StringTrimRight, %root%_children, %root%_children, 1
  Loop, Parse, %root%_children, `n
  {
    If %root%_%A_LoopField%_children
      xml .= serialize(%root%_%A_LoopField%)
    Else
    {
      element := "<" . %root%_%A_LoopField%_name . ">"
      element .= %root%_%A_LoopField%_text
      element .= "</" . %root%_%A_LoopField%_name . ">"
      xml .= element
    }
  }
  Return xml .= "</" . root%root0% . ">"
}

Bracmat

To produce the XML including all indentations, we can do this:

(     ("?"."xml version=\"1.0\" ")
      \n
      (root.,"\n    " (element.,"
        Some text here
    ") \n)
  : ?xml
& out$(toML$!xml)
);

If we do not care about indentation:

(   ("?"."xml version=\"1.0\"") (root.,(element.,"Some text here"))
  : ?xml
& out$(toML$!xml)
);

C

Library: LibXML

#include <libxml/parser.h>
#include <libxml/tree.h>
  
int main()
{
  xmlDoc *doc = xmlNewDoc("1.0");
  xmlNode *root = xmlNewNode(NULL, BAD_CAST "root");
  xmlDocSetRootElement(doc, root);

  xmlNode *node = xmlNewNode(NULL, BAD_CAST "element");
  xmlAddChild(node, xmlNewText(BAD_CAST "some text here"));
  xmlAddChild(root, node);

  xmlSaveFile("myfile.xml", doc);
 
  xmlFreeDoc(doc);
  xmlCleanupParser();
}

Library: Gadget

Version 1 (48 allocs):

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String XML, body;
   Stack{
       Store ( XML, Parser( "element", "","Some text here", NORMAL_TAG) );
       Store ( XML, Parser( "root", "",XML, NORMAL_TAG) );
   } Stack_off;
   
   body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
   Print "%s\n", body;
   
   Free secure XML, body;
End

Version 2 (46 allocs):

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String XML, body;
   
   Get_fn_let( XML, Parser( "element", "","Some text here", NORMAL_TAG) );
   Get_fn_let( XML, Parser( "root", "",XML, NORMAL_TAG) );
   
   body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
   Print "%s\n", body;
   
   Free secure XML, body;
End

Version 3 (47 allocs):

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String XML, body;
   Stack{
       Store ( XML, Parser( "root", "", 
                    Parser( "element", "","Some text here", NORMAL_TAG), 
                    NORMAL_TAG) );
   } Stack_off;
   
   body = Multi_copy( body,"<?xml version=\"1.0\" ?>", XML, NULL);
   Print "%s\n", body;
   
   Free secure XML, body;
End

Version 4 (50 allocs):

#include <gadget/gadget.h>

LIB_GADGET_START

Main
   String body;
   Stack{
       Store ( body, Multi_copy( body,"<?xml version=\"1.0\" ?>", 
                                 Parser( "root", "", Parser( "element", "","Some text here", 
                                 NORMAL_TAG), NORMAL_TAG), 
                                 NULL) );
   }

   Print "%s\n", body;
   
   Free secure body;
End
Output:
$ ./tests/RC_dom 
<?xml version="1.0" ?><root><element>Some text here</element></root>

C#

Serialization using the built-in System.Xml.Serialization library of .Net.

using System.Xml;
using System.Xml.Serialization;
[XmlRoot("root")]
public class ExampleXML
{
    [XmlElement("element")]
    public string element = "Some text here";
    static void Main(string[] args)
    {
        var xmlnamespace = new XmlSerializerNamespaces();
        xmlnamespace.Add("", ""); //used to stop default namespaces from printing
        var writer = XmlWriter.Create("output.xml");
        new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace);
    }
    //Output: <?xml version="1.0" encoding="utf-8"?><root><element>Some text here</element></root>
}

C++

Library: LibXML
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlsave.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>

#ifndef LIBXML_TREE_ENABLED
#   error libxml was not configured with DOM tree support
#endif

#ifndef LIBXML_OUTPUT_ENABLED
#   error libxml was not configured with serialization support
#endif

// Because libxml2 is a C library, we need a couple things to make it work
// well with modern C++:
//   1) a ScopeGuard-like type to handle cleanup functions; and
//   2) an exception type that transforms the library's errors.

// ScopeGuard-like type to handle C library cleanup functions.
template <typename F>
class [[nodiscard]] scope_exit
{
public:
    // C++20: Constructor can (and should) be [[nodiscard]].
    /*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :
        f_{std::move(f)}
    {}

    ~scope_exit()
    {
        f_();
    }

    // Non-copyable, non-movable.
    scope_exit(scope_exit const&) = delete;
    scope_exit(scope_exit&&) = delete;
    auto operator=(scope_exit const&) -> scope_exit& = delete;
    auto operator=(scope_exit&&) -> scope_exit& = delete;

private:
    F f_;
};

// Exception that gets last libxml2 error.
class libxml_error : public std::runtime_error
{
public:
    libxml_error() : libxml_error(std::string{}) {}

    explicit libxml_error(std::string message) :
        std::runtime_error{make_message_(std::move(message))}
    {}

private:
    static auto make_message_(std::string message) -> std::string
    {
        if (auto const last_error = ::xmlGetLastError(); last_error)
        {
            if (not message.empty())
                message += ": ";
            message += last_error->message;
        }

        return message;
    }
};

auto add_text(::xmlNode* node, ::xmlChar const* content)
{
    // Create a new text node with the desired content.
    auto const text_node = ::xmlNewText(content);
    if (not text_node)
        throw libxml_error{"failed to create text node"};

    // Try to add it to the node. If it succeeds, that node will take
    // ownership of the text node. If it fails, we have to clean up the text
    // node ourselves first, then we can throw.
    if (auto const res = ::xmlAddChild(node, text_node); not res)
    {
        ::xmlFreeNode(text_node);
        throw libxml_error{"failed to add text node"};
    }
    
    return text_node;
}

auto main() -> int
{
    // Set this to true if you don't want the XML declaration.
    constexpr auto no_xml_declaration = false;

    try
    {
        // Initialize libxml.
        ::xmlInitParser();
        LIBXML_TEST_VERSION
        auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};

        // Create a new document.
        auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8"1.0"));
        if (not doc)
            throw libxml_error{"failed to create document"};
        auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};

        // Create the root element.
        auto root = ::xmlNewNode(nullptr,
            reinterpret_cast<::xmlChar const*>(u8"root"));
        if (not root)
            throw libxml_error{"failed to create root element"};
        ::xmlDocSetRootElement(doc, root); // doc now owns root

        // Add whitespace. Unless you know the whitespace is not significant,
        // you should do this manually, rather than relying on automatic
        // indenting.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n    "));

        // Add the child element.
        if (auto const res = ::xmlNewTextChild(root, nullptr,
                reinterpret_cast<::xmlChar const*>(u8"element"),
                reinterpret_cast<::xmlChar const*>(
                    u8"\n        Some text here\n    "));
                not res)
            throw libxml_error{"failed to create child text element"};

        // Add whitespace.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n"));

        // Output tree. Note that the output is UTF-8 in all cases. If you
        // want something different, use xmlSaveFileEnc() or the second
        // argument of xmlSaveDoc().
        if constexpr (no_xml_declaration)
        {
            auto const save_context = ::xmlSaveToFilename("-", nullptr,
                XML_SAVE_NO_DECL);
            auto const save_context_cleanup = scope_exit{[save_context] {
                ::xmlSaveClose(save_context); }};

            if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
        else
        {
            if (auto const res = ::xmlSaveFile("-", doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
    }
    catch (std::exception const& x)
    {
        std::cerr << "ERROR: " << x.what() << '\n';
        return EXIT_FAILURE;
    }
}

Caché ObjectScript

USER>set writer=##class(%XML.Writer).%New()
USER>set writer.Charset="UTF-8"
USER>Set writer.Indent=1
USER>Set writer.IndentChars="    "
USER>set sc=writer.OutputToString()
USER>set sc=writer.RootElement("root")
USER>set sc=writer.Element("element")
USER>set sc=writer.WriteChars("Some text here")
USER>set sc=writer.EndElement()
USER>set sc=writer.EndRootElement()
USER>Write writer.GetXMLString()

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <element>Some text here</element>
</root>

Clojure

(require '[clojure.data.xml :as xml])

(def xml-example (xml/element :root {} (xml/element :element {} "Some text here")))

(with-open [out-file (java.io.OutputStreamWriter.
                        (java.io.FileOutputStream. "/tmp/output.xml") "UTF-8")]
  (xml/emit xml-example out-file))
Output:
<?xml version="1.0" encoding="UTF-8"?><root><element>Some text here</element></root>

Common Lisp

Library: Closure XML

Assuming that matching the whitespace in the problem description isn't necessary and that character encodings are permitted (see the talk page):

(let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil))
       (root (dom:create-element doc "root"))
       (element (dom:create-element doc "element"))
       (text (dom:create-text-node doc "Some text here")))
  (dom:append-child element text)
  (dom:append-child root element)
  (dom:append-child doc root)
  (dom:map-document (cxml:make-rod-sink) doc))

gives the following output:

<?xml version="1.0" encoding="UTF-8"?>
<root><element>Some text here</element></root>

Because dom:append-child returns the appended child, the same output can be produced while binding fewer variables:

(let ((doc (dom:create-document 'rune-dom:implementation nil nil nil)))
  (dom:append-child
   (dom:append-child
    (dom:append-child doc (dom:create-element doc "root"))
    (dom:create-element doc "element"))
   (dom:create-text-node doc "Some text here"))
  (write-string (dom:map-document (cxml:make-rod-sink) doc)))

The prefix notation makes this hard to decipher, however, and so a final version uses an auxiliary append-child*:

(defun append-child* (parent &rest children)
  (reduce 'dom:append-child children :initial-value parent))

(let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil)))
  (append-child* doc
                 (dom:create-element doc "root")
                 (dom:create-element doc "element")
                 (dom:create-text-node doc "Some text here"))
  (write-string (dom:map-document (cxml:make-rod-sink) doc)))

D

Works with: D version 2.011+
module xmltest ;

import std.stdio ;
import std.xml ;

void main() {
  auto doc = new Document("root") ;
//doc.prolog = q"/<?xml version="1.0"?>/" ; // default
  doc ~= new Element("element", "Some text here") ;
  writefln(doc) ;
// output: <?xml version="1.0"?><root><element>Some text here</element></root>
}

E

Works with: E-on-Java

This makes use of XML libraries provided with Java.

def document := <unsafe:javax.xml.parsers.makeDocumentBuilderFactory> \
                  .newInstance() \
                  .newDocumentBuilder() \
                  .getDOMImplementation() \
                  .createDocument(null, "root", null)
def root := document.getDocumentElement()
root.appendChild(
  def element := document.createElement("element"))
element.appendChild(
  document.createTextNode("Some text here"))
println(document.saveXML(root))

(On the use of <unsafe>: The class has not yet been reviewed for E safety, so <import:...makeDocumentBuilderFactory> is not yet allowed. The review would probably be straightforward.)

FreeBASIC

Library: libxml2
#include once "crt/stdio.bi"
#include once "crt/stdlib.bi"
#include once "libxml/tree.bi"
#include once "libxml/parser.bi"

'' Create a new document
Dim As xmlDocPtr doc = xmlNewDoc(Strptr("1.0"))

'' Create a root node
Dim As xmlNodePtr root_node = xmlNewNode(NULL, Strptr("root"))

'' Set the root node for the document
xmlDocSetRootElement(doc, root_node)

'' Create a new node
Dim As xmlNodePtr node = xmlNewNode(NULL, Strptr("element"))

'' Add some text to the node
xmlNodeSetContent(node, Strptr("Some text here"))

'' Add the new node to the root node
xmlAddChild(root_node, node)

'' Dump the document to stdout, it will be well formatted
xmlDocDump(stdout, doc)

'' Free the document
xmlFreeDoc(doc)

'' Free the global variables that may have been allocated by the parser
xmlCleanupParser()

F#

open System.Xml

[<EntryPoint>]
let main argv =
    let xd = new XmlDocument()
    // Create the required nodes:
    xd.AppendChild (xd.CreateXmlDeclaration("1.0", null, null)) |> ignore
    let root = xd.AppendChild (xd.CreateNode("element", "root", ""))
    let element = root.AppendChild (xd.CreateElement("element", "element", ""))
    element.AppendChild (xd.CreateTextNode("Some text here")) |> ignore
    // The same can be accomplished with:
    // xd.LoadXml("""<?xml version="1.0"?><root><element>Some text here</element></root>""")

    let xw = new XmlTextWriter(System.Console.Out)
    xw.Formatting <- Formatting.Indented
    xd.WriteContentTo(xw)
    0

Output

<?xml version="1.0"?>
<root>
  <element>Some text here</element>
</root>

Factor

USING: xml.syntax xml.writer ;

<XML <root><element>Some text here</element></root> XML>
pprint-xml
Output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <element>
    Some text here
  </element>
</root>

Factor's XML syntax isn't just for parsing static XML. Since it supports interpolation (denoted by <->) and plays nicely with sequences, it is easy to build up arbitrary trees:

USING: sequences xml.syntax xml.writer ;

3 [XML <element>Some text here</element> XML] <repetition>
[XML <element2><element3>1.0</element3></element2> XML] append
<XML <root><-></root> XML>
pprint-xml
Output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <element>
    Some text here
  </element>
  <element>
    Some text here
  </element>
  <element>
    Some text here
  </element>
  <element2>
    <element3>
      1.0
    </element3>
  </element2>
</root>

Fantom

using xml
 
class XmlDom
{
  public static Void main ()
  {
    doc := XDoc()
    root := XElem("root")
    doc.add (root)
 
    child := XElem("element")
    child.add(XText("Some text here"))
    root.add (child)
 
    doc.write(Env.cur.out)
  }
}

Output:

<?xml version='1.0' encoding='UTF-8'?>
<root>
 <element>Some text here</element>
</root>

Forth

include ffl/dom.fs

\ Create a dom variable 'doc' in the dictionary

dom-create doc

\ Add the document root with its version attribute

dom.document doc dom-append-node

s" version" s" 1.0" dom.attribute doc dom-append-node

\ Add root and element

doc dom-parent 2drop

s" root"    dom.element doc dom-append-node

s" element" dom.element doc dom-append-node

\ Add the text

s" Some text here" dom.text doc dom-append-node

\ Convert the document to a string and print

doc dom-write-string [IF]
  type cr
[THEN]

Go

A very small, subset of the W3C DOM Core in Go. The work builds off the existing XML parser. A fork of the godom project (http://code.google.com/p/godom/), which appears to be unsupported at the moment.

package main

import (
    "fmt"
    dom "gitlab.com/stone.code/xmldom-go.git"
)

func main() {
    d, err := dom.ParseStringXml(`
<?xml version="1.0" ?>
<root>
    <element>
        Some text here
    </element>
</root>`)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(d.ToXml()))
}
Output:
<root>
    <element>
        Some text here
    </element>
</root>

Groovy

import groovy.xml.MarkupBuilder
def writer = new StringWriter() << '<?xml version="1.0" ?>\n'
def xml = new MarkupBuilder(writer)
xml.root() {
    element('Some text here' ) 
}
println writer

Haskell

Using the XML.Light module from HackageDB

import Data.List
import Text.XML.Light

xmlDOM :: String -> String
xmlDOM txt = showTopElement $ Element
    (unqual "root")
    []
    [ Elem $ Element
      (unqual "element")
      []
      [Text $ CData CDataText txt Nothing]
      Nothing
    ]
    Nothing

Output:

*Main> mapM_ (putStrLn.ppContent) $ parseXML (xmlDOM "  Some text  ")
<?xml version="1.0" ?>
<root>
  <element>  Some text  </element>
</root>

J

There are probably better ways of doing this, but, here is a simple serializer for a rudimentary concept of a dom:

serialize=: ('<?xml version="1.0" ?>',LF),;@serialize1&''
serialize1=:4 :0
  if.L.x do.
    start=. y,'<',(0{::x),'>',LF
    middle=. ;;(}.x) serialize1&.> <'    ',y
    end=. y,'</',(0{::x),'>',LF
    <start,middle,end
  else.
    <y,x,LF
  end.
)

And here is a document object that matches this task:

obj=: 'root';<'element';'some text here'

Example use:

   serialize obj
<?xml version="1.0" ?>
<root>
    <element>
        some text here
    </element>
</root>

Java

Java's XML DOM tools don't really allow total control of the output format "out of the box" but the following program generates XML that is equivalent to the required output.

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class RDOMSerialization {

  private Document domDoc;

  public RDOMSerialization() {
    return;
  }

  protected void buildDOMDocument() {

    DocumentBuilderFactory factory;
    DocumentBuilder builder;
    DOMImplementation impl;
    Element elmt1;
    Element elmt2;

    try {
      factory = DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
      impl = builder.getDOMImplementation();
      domDoc = impl.createDocument(null, null, null);
      elmt1 = domDoc.createElement("root");
      elmt2 = domDoc.createElement("element");
      elmt2.setTextContent("Some text here");

      domDoc.appendChild(elmt1);
      elmt1.appendChild(elmt2);
    }
    catch (ParserConfigurationException ex) {
      ex.printStackTrace();
    }

    return;
  }

  protected void serializeXML() {

    DOMSource domSrc;
    Transformer txformer;
    StringWriter sw;
    StreamResult sr;

    try {
      domSrc = new DOMSource(domDoc);

      txformer = TransformerFactory.newInstance().newTransformer();
      txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      txformer.setOutputProperty(OutputKeys.METHOD, "xml");
      txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      txformer.setOutputProperty(OutputKeys.INDENT, "yes");
      txformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
      txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      sw = new StringWriter();
      sr = new StreamResult(sw);

      txformer.transform(domSrc, sr);

      System.out.println(sw.toString());
    }
    catch (TransformerConfigurationException ex) {
      ex.printStackTrace();
    }
    catch (TransformerFactoryConfigurationError ex) {
      ex.printStackTrace();
    }
    catch (TransformerException ex) {
      ex.printStackTrace();
    }

    return;
  }

  public static void serializationDriver(String[] args) {

    RDOMSerialization lcl = new RDOMSerialization();
    lcl.buildDOMDocument();
    lcl.serializeXML();

    return;
  }

  public static void main(String[] args) {
    serializationDriver(args);
    return;
  }
}

Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
  <element>Some text here</element>
</root>

JavaScript

Works with: Firefox version 2.0

DOM

var doc = document.implementation.createDocument( null, 'root', null );
var root = doc.documentElement;
var element = doc.createElement( 'element' );
root.appendChild( element );
element.appendChild( document.createTextNode('Some text here') );
var xmlString = new XMLSerializer().serializeToString( doc );

E4X

var xml = <root>
  <element>Some text here</element>
</root>;
var xmlString = xml.toXMLString();

E4X — with processing instruction

XML.ignoreProcessingInstructions = false;
var xml = <?xml version="1.0"?>  
<root>
  <element>Some text here</element>
</root>;
var xmlString = xml.toXMLString();

Julia

using LightXML

# Modified from the documentation for LightXML.jl. The underlying library requires an encoding string be printed.

# create an empty XML document
xdoc = XMLDocument()

# create & attach a root node
xroot = create_root(xdoc, "root")

# create the first child
xs1 = new_child(xroot, "element")

# add the inner content
add_text(xs1, "some text here")

println(xdoc)
Output:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>some text here</element>
</root>

Kotlin

This is the closest I could get to the required output.

There appears to be no satisfactory way to prevent the default encoding and standalone attributes from appearing in the XML declaration using the standard JDK DOM implementation. If you set the standalone attribute to true - using doc.setXmlStandalone(true) - then this removes it from the declaration but unfortunately there is then no carriage return before the <root> tag!

So I've decided to leave it as it is.

// 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 dbFactory = DocumentBuilderFactory.newInstance()
    val dBuilder  = dbFactory.newDocumentBuilder()
    val doc = dBuilder.newDocument()
    val root = doc.createElement("root")  // create root node
    doc.appendChild(root)
    val element = doc.createElement("element")  // create element node
    val text = doc.createTextNode("Some text here")  // create text node
    element.appendChild(text)
    root.appendChild(element)

    // serialize
    val source = DOMSource(doc)
    val sw = StringWriter()
    val result = StreamResult(sw)
    val tFactory = TransformerFactory.newInstance()
    tFactory.newTransformer().apply {
        setOutputProperty("indent", "yes")
        setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4") 
        transform(source, result)
    }
    println(sw)            
}
Output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <element>Some text here</element>
</root>

Lasso

content_type( 'text/xml' );// set MIME type if serving

xml( '<?xml version="1.0" ?><root><element>Some text here</element></root>' );

Lingo

Code based on Flash Xtra (comes with Director, i.e. "built-in") that allows to use AS2/AS3 classes in Lingo (in this case "XML" is an AS2 class).

-- create an XML document
doc = newObject("XML", "<?xml version='1.0' ?>")

root = doc.createElement("root")  
doc.appendChild(root)

element = doc.createElement("element")
root.appendChild(element)

textNode = doc.createTextNode("Some text here")
element.appendChild(textNode)

put doc.toString()
-- "<?xml version='1.0' ?><root><element>Some text here</element></root>"

Lua

Using the widely available 'LuaXML' module

require("LuaXML")
local dom = xml.new("root")
local element = xml.new("element")
table.insert(element, "Some text here")
dom:append(element)
dom:save("dom.xml")

Resulting contents of dom.xml:

<?xml version="1.0"?>
<!-- file "dom.xml", generated by LuaXML -->

<root>
  <element>Some text here</element>
</root>

Mathematica/Wolfram Language

DOM = XMLObject["Document"][{XMLObject["Declaration"]["Version" -> "1.0","Encoding" -> "utf-8"]},
XMLElement["root", {}, {XMLElement["element", {}, {"Some text here"}]}], {}];
ExportString[DOM, "XML", "AttributeQuoting" -> "\""]
Output:
<?xml version="1.0" encoding="utf-8"?>
<root>
 <element>Some text here</element>
</root>

MATLAB

docNode = com.mathworks.xml.XMLUtils.createDocument('root');
docRootNode = docNode.getDocumentElement;
thisElement = docNode.createElement('element'); 
thisElement.appendChild(docNode.createTextNode('Some text here'));
docRootNode.appendChild(thisElement);

Output:

 xmlwrite(docNode)

ans =

<?xml version="1.0" encoding="utf-8"?>
<root>
   <element>Some text here</element>
</root>

NetRexx

Translation of: Java
/* NetRexx */
options replace format comments java crossref symbols nobinary

import java.io.StringWriter
import javax.xml.
import org.w3c.dom.

class RDOMSerialization public

properties private
  domDoc = Document

method main(args = String[]) public static

  lcl = RDOMSerialization()
  lcl.buildDOMDocument()
  lcl.serializeXML()

  return

method buildDOMDocument() inheritable

  do
    factory = DocumentBuilderFactory.newInstance()
    builder = factory.newDocumentBuilder()
    impl = builder.getDOMImplementation()
    domDoc = impl.createDocument(null, null, null)
    elmt1 = domDoc.createElement("root")
    elmt2 = domDoc.createElement("element")
    elmt2.setTextContent("Some text here")

    domDoc.appendChild(elmt1)
    elmt1.appendChild(elmt2)
  
  catch exPC = ParserConfigurationException
    exPC.printStackTrace
  end
  
  return

method serializeXML() inheritable

  do
    domSrc = DOMSource(domDoc)
    txformer = TransformerFactory.newInstance().newTransformer()
    txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no")
    txformer.setOutputProperty(OutputKeys.METHOD, "xml")
    txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")
    txformer.setOutputProperty(OutputKeys.INDENT, "yes")
    txformer.setOutputProperty(OutputKeys.STANDALONE, "yes")
    txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
  
    sw = StringWriter()
    sr = StreamResult(sw)
  
    txformer.transform(domSrc, sr)
  
    say sw.toString

  catch exTC = TransformerConfigurationException
    exTC.printStackTrace
  catch exTF = TransformerFactoryConfigurationError
    exTF.printStackTrace
  catch exTE = TransformerException
    exTE.printStackTrace
  end

  return

Output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
  <element>Some text here</element>
</root>

Nim

Library: nim-xmldom

Note that the module “xmldom” is no longer part of the standard library as more convenient modules are now available. It can be installed using the package manager nimble.

import xmldom

var
  dom = getDOM()
  document = dom.createDocument("", "root")
  topElement = document.documentElement
  firstElement = document.createElement "element"
  textNode = document.createTextNode "Some text here"

topElement.appendChild firstElement
firstElement.appendChild textNode

echo document

Output:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <element>
    Some text here
  </element>
</root>

Objeck

use XML;

bundle Default {
  class Test {
    function : Main(args : String[]) ~ Nil {
      builder := XMLBuilder->New("root", "1.0");
      root := builder->GetRoot();
      element := XMLElement->New(XMLElementType->ELEMENT, "element", "Some text here");
      root->AddChild(element);
      builder->ToString()->PrintLine();
    }
  }
}

OpenEdge/Progress

The following example uses the X-DOCUMENT, for faster processing SAX can be used.

DEFINE VARIABLE hxdoc      AS HANDLE NO-UNDO.
DEFINE VARIABLE hxroot     AS HANDLE NO-UNDO.
DEFINE VARIABLE hxelement  AS HANDLE NO-UNDO.
DEFINE VARIABLE hxtext     AS HANDLE NO-UNDO.
DEFINE VARIABLE lcc        AS LONGCHAR NO-UNDO.

CREATE X-DOCUMENT hxdoc.

CREATE X-NODEREF hxroot.
hxdoc:CREATE-NODE( hxroot, 'root', 'ELEMENT' ).
hxdoc:APPEND-CHILD( hxroot ).

CREATE X-NODEREF hxelement.
hxdoc:CREATE-NODE( hxelement, 'element', 'ELEMENT' ).
hxroot:APPEND-CHILD( hxelement ).

CREATE X-NODEREF hxtext.
hxdoc:CREATE-NODE( hxtext, 'element', 'TEXT' ).
hxelement:APPEND-CHILD( hxtext ).
hxtext:NODE-VALUE = 'Some text here'.

hxdoc:SAVE( 'LONGCHAR', lcc ).
MESSAGE STRING( lcc ) VIEW-AS ALERT-BOX.

Oz

With the code from XML Creation#Oz, we can write:

declare
  proc {Main}
   DOM = root(element("Some text here"))
  in
     {System.showInfo {Serialize DOM}}
  end
  ...

Output:

<?xml version="1.0" ?>
<root>
    <element>Some text here</element>
</root>

Pascal

Works with: Free_Pascal
Library: Classes
Library: XMLWrite
Library: DOM
program CrearXML;

{$mode objfpc}{$H+}

uses
  Classes, XMLWrite, DOM;

var
  xdoc: TXMLDocument;                                  // variable objeto documento XML
  NodoRaiz, NodoPadre, NodoHijo: TDOMNode;             // variables a los nodos
begin
  //crear el documento
  xdoc := TXMLDocument.create;

  NodoRaiz := xdoc.CreateElement('root');               // crear el nodo raíz
  Xdoc.Appendchild(NodoRaiz);                           // guardar nodo raíz
  NodoPadre := xdoc.CreateElement('element');           // crear el nodo hijo
  NodoHijo := xdoc.CreateTextNode('Some text here');    // insertar el valor del nodo
  NodoPadre.Appendchild(NodoHijo);                      // guardar nodo
  NodoRaiz.AppendChild(NodoPadre);                      // insertar el nodo hijo en el correspondiente nodo padre
  writeXMLFile(xDoc,'prueba.xml');                      // escribir el XML
  NodoRaiz.free;
  NodoPadre.free; 
  NodoHijo.free;  
  Xdoc.free;
end.

Output:

<?xml version="1.0"?>
<root>
  <element>Some text here</element>
</root>.

Perl

use XML::Simple;
print XMLout( { root => { element => "Some text here" } }, NoAttr => 1, RootName => "" );

Output:

<root>
  <element>Some text here</element>
</root>
use XML::DOM::BagOfTricks qw(createDocument createTextElement);

my ($doc, $root) = createDocument('root');
$root->appendChild(
    createTextElement($doc, 'element', 'Some text here')
);
print $doc->toString;

Output:

<root><element>Some text here</element></root>
Library: LibXML
use XML::LibXML;

$xml = XML::LibXML::Document->new('1.0');
$node = $xml->createElement('root');
$xml->setDocumentElement($node);
$node2 = $xml->createElement('element');
$text = $xml->createTextNode('Some text here');
$node2->addChild($text);
$node->appendWellBalancedChunk('text');
$node->addChild($node2);

print $xml->toString;

Output:

<?xml version="1.0"?>
<root>text<element>Some text here</element></root>

Phix

with javascript_semantics
include builtins/xml.e
sequence elem = xml_new_element("element", "Some text here"),
         root = xml_new_element("root", {elem}),
         doc = xml_new_doc(root,{`<?xml version="1.0" ?>`})
puts(1,xml_sprint(doc))
Output:
<?xml version="1.0" ?>
<root>
  <element>Some text here</element>
</root>

If only one parameter is supplied to xml_new_doc(), the output includes the default `encoding="utf-8" `.

PHP

Works with: PHP version 5
<?php
$dom = new DOMDocument();//the constructor also takes the version and char-encoding as it's two respective parameters
$dom->formatOutput = true;//format the outputted xml
$root = $dom->createElement('root');
$element = $dom->createElement('element');
$element->appendChild($dom->createTextNode('Some text here'));
$root->appendChild($element);
$dom->appendChild($root);
$xmlstring = $dom->saveXML();

PicoLisp

(load "@lib/xm.l")

(xml? T)
(xml '(root NIL (element NIL "Some text here")))

Output:

<?xml version="1.0" encoding="utf-8"?>
<root>
   <element>Some text here</element>
</root>

Pike

manually, one node at a time:

object dom = Parser.XML.Tree.SimpleRootNode();
dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), ""));
object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "root", ([]), "");
dom->add_child(node);

object subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "element", ([]), "");
node->add_child(subnode);

node = subnode;
subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "Some text here");
node->add_child(subnode);

dom->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?><root><element>Some text here</element></root>"

from an array, using a conversion function:

object make_xml_node(array|string in, void|int level)
{
    level++;
    if (stringp(in))
        return Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), in);
    else
    {
        object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, in[0], in[1], ""); 
        foreach(in[2..];; array|string child)
        {
            node->add_child(make_xml_node(child, level));
        }
        return node;
    }
}

object make_xml_tree(array input)
{
    object dom = Parser.XML.Tree.SimpleRootNode();
    dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), ""));
    dom->add_child(make_xml_node(input));
    return dom;
}

array input = ({ "root", ([]), ({ "element", ([]), "Some text here" }) });
make_xml_tree(input)->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?><root><element>Some text here</element></root>"

to render the output with indenting as specified in the task, this function adds the necessary text nodes:

object indent_xml(object parent, void|int indent_text, void|int level)
{
    int subnodes = false; 
    foreach(parent->get_children();; object child)
    {
        if (child->get_node_type() == Parser.XML.Tree.XML_ELEMENT || 
            (child->get_node_type() == Parser.XML.Tree.XML_TEXT && indent_text))
        {
            subnodes = true; 
            parent->add_child_before(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "\r\n"+"    "*level), child); 
            indent_xml(child, indent_text, level+1);
        }
    }
    if (subnodes && level)
        parent->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "\r\n"+"    "*(level-1)));
    return parent;
} 


indent_xml(make_xml_tree(input))->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?>\r\n"
        "<root>\r\n"
        "    <element>Some text here</element>\r\n"
        "</root>"

indent_xml(make_xml_tree(input), 1)->render_xml();
Result: "<?xml version='1.0' encoding='utf-8'?>\r\n"
        "<root>\r\n"
        "    <element>\r\n"
        "        Some text here\r\n"
        "    </element>\r\n"
        "</root>"

Python

Works with: Python version 2.5
from xml.dom.minidom import getDOMImplementation

dom = getDOMImplementation()
document = dom.createDocument(None, "root", None)

topElement = document.documentElement
firstElement = document.createElement("element")
topElement.appendChild(firstElement)
textNode = document.createTextNode("Some text here")
firstElement.appendChild(textNode)

xmlString = document.toprettyxml(" " * 4)
from xml.etree import ElementTree as et

root = et.Element("root")
et.SubElement(root, "element").text = "Some text here"
xmlString = et.tostring(root)

Racket

#lang at-exp racket
(require xml)

(define xml-str
  @~a{<?xml version="1.0" ?>
       <root>
           <element>
               Some text here
           </element>
       </root>})

;; read & parse to get an xml value
(define xml (read-xml/document (open-input-string xml-str)))
;; print it out in xml form, which is identical to the input xml
(write-xml xml)
(newline)

Raku

(formerly Perl 6)

Works with: Rakudo version 2018.05
use XML;
use XML::Writer;

say my $document = XML::Document.new(
    XML::Writer.serialize( :root[ :element['Some text here', ], ] )
);
Output:
<?xml version="1.0"?><root><element>Some text here</element></root>

Rascal

import lang::xml::DOM;

public void main(){
	x = document(element(none(), "root", [element(none(), "element", [charData("Some text here")])]));
	return println(xmlPretty(x));
}

Output example:

rascal>main()
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <element>Some text here</element>
</root>

Ruby

Library: REXML
require("rexml/document")
include REXML
(doc = Document.new) << XMLDecl.new
root = doc.add_element('root')
element = root.add_element('element')
element.add_text('Some text here')

# save to a string 
# (the first argument to write() needs an object that understands "<<")
serialized = String.new
doc.write(serialized, 4)
puts serialized

produces

<?xml version='1.0'?>
<root>
    <element>
        Some text here
    </element>
</root>

Scala

val xml = <root><element>Some text here</element></root>
scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null)

Sidef

Translation of: Perl
require('XML::Simple');
print %S'XML::Simple'.XMLout(
    :(root => :( element => 'Some text here' )),
    NoAttr => 1, RootName => '',
);
Output:
  <root>
    <element>Some text here</element>
  </root>

Tcl

Library: tDOM
package require tdom
set d [dom createDocument root]
set root [$d documentElement]
$root appendChild [$d createElement element]
[$root firstChild] appendChild [$d createTextNode "Some text here"]
$d asXML
<root>
    <element>Some text here</element>
</root>

Using TclDOM

package require dom
set doc [dom::DOMImplementation create]
set root [dom::document createElement $doc root]
set elem [dom::document createElement $root element]
set text [dom::document createTextNode $elem "Some text here"]
dom::DOMImplementation serialize $doc -newline {element}
<?xml version='1.0'?>
<!DOCTYPE root>
<root>
<element>
Some text here
</element>
</root>

Wren

Wren has no built-in or (AFAIK) third party support for XML so we code a minimal DOM sufficient for completing this task.

class XmlDocument {
    construct new(root) {
        _root = root
    }

    toString { "<?xml version=\"1.0\" ?>\n%(_root.toString(0))" }
}

class XmlElement {
    construct new(name, text) {
        _name = name
        _text = text
        _children = []
    }

    name     { _name }
    text     { _text }
    children { _children }

    addChild(child) { _children.add(child) }

    toString(level) {
        var indent = "    "
        var s = indent * level + "<%(name)>\n"
        if (_text != "") s = s + indent * (level + 1) + _text + "\n"
        for (c in _children) {
            s = s + c.toString(level+1) + "\n"
        }
        return s + indent * level + "</%(name)>"
    }
}

var root  = XmlElement.new("root", "")
var child = XmlElement.new("element", "Some text here")
root.addChild(child)
var doc = XmlDocument.new(root)
System.print(doc)
Output:
<?xml version="1.0" ?>
<root>
    <element>
        Some text here
    </element>
</root>


Since the first version was written, the above XML parser has appeared and, consequently, the solution can now be rewritten as follows.

import "./xsequence" for XDocument, XElement

var doc = XDocument.new(
    XElement.new("root",
        XElement.new("element", "Some text here")
    )
)
System.print(doc)
Output:
<?xml version="1.0" encoding="utf-8"?>
<root>
  <element>Some text here</element>
</root>

XProc

<p:pipeline xmlns:p="http://www.w3.org/ns/xproc" version="1.0">
  <p:identity>
    <p:input port="source">
      <p:inline>
        <root>
          <element>
            Some text here
          </element>
        </root>
      </p:inline>
    </p:input>
  </p:identity>
</p:pipeline>

XQuery

In XQuery static element construction is like normal XML:

<root>
  <element>
    Some text here
  </element>
</root>

Dynamic element construction looks quite different:

let $rootTagname := 'root'
let $elementTagname := 'element'
let $elementContent := 'Some text here'

return
  element {$rootTagname}
          {
            element{$elementTagname}
                   {$elementContent}
          }

XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" />
  <xsl:template match="/">   <!-- replace the root of the incoming document with our own model -->
    <xsl:element name="root">
      <xsl:element name="element">
        <xsl:text>Some text here</xsl:text>
      </xsl:element>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

Z80 Assembly

Assembled and run using WinAPE's built-in assembler. Tags have to be manually opened and closed, but it works!

org &1000
main:
ld hl,XML_Header
ld de,XMLRam
call strcpy

ld hl,XML_Root
push hl
call AddXMLNode

ld hl,XML_Element
push hl
call AddXMLNode

ld hl,XML_Entry
call strcpy

pop hl  ;ld hl,XML_Element
call CloseXMLNode

pop hl  ;ld hl,XML_Root
call CloseXMLNode

ld hl,XMLRam
jp PrintString  ;and then return to basic.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
AddXMLNode:
;hl = pointer to desired node name
;de = destination ram
;carry flag; set = <foo/>, clear = <foo></foo>
push af
ld a,'<'
ld (de),a
inc de
call strcpy
pop af
jr nc,skip_AddXMLNode
ld a,'/'
ld (de),a
inc de
skip_AddXMLNode:
ld a,'>'
ld (de),a
inc de
xor a
ld (de),a
;don't inc de afterwards, since we may want to add more
ret

CloseXMLNode:
ld a,'<'
ld (de),a
inc de
ld a,'/'
ld (de),a
inc de
call strcpy
ld a,'>'
ld (de),a
inc de
xor a
ld (de),a
ret

PrintString:
	ld a,(hl)
	or a
	ret z
	call &BB5A
	inc hl
	jr PrintString

strcpy:
;HL = string source
;DE = destination
;copies 1 byte at a time until a null terminator is copied, then exits.
ld a,(hl)
ld (de),a
or a
ret z
inc hl
inc de
jp strcpy

org &1200
XML_Header:
byte "<?xml version=",&22,"1.0",&22,"?>",0
XML_Root:
byte "root",0
XML_Element:
byte "element",0
XML_Entry:
byte "some text here",0

org &1300
XMLRam:  ;this is where the output is stored.
Output:
call &1000
<?xml version="1.0"?><root><element>some text here</element></root>