expat(n)
okay bestie, welcome to expat(n) β the manual page for the command that spins up an expat parser object. buckle up, it's giving very thorough π
πΈ NAME πΈ
expat β creates an instance of an expat parser object. that's it, that's the job. β¨
π SYNOPSIS π
package require tdom
expat ?parsername? ?-namespace? ?arg arg ..
xml::parser ?parsername? ?-namespace? ?arg arg ..
π« DESCRIPTION π«
so the parser you make with expat or xml::parser (which is literally just another name for the same command, living in its own namespace, no drama) can parse any kind of well-formed XML. these are stream oriented XML parsers, meaning: you register handler scripts with the parser before you start the parse, and those handler scripts get called whenever the parser discovers the matching structures in the document it's chewing through. a start tag is a classic example of the kind of structure you'd register a handler script for. π
these parsers always check the input for XML well-formedness (and they will report an error if the input isn't well-formed, no cap). they parse the internal DTD and, on request, the external DTD and external entities too β but only if you resolve the identifier of the external entities with the -externalentitycommand script (go read that bit π). and if you use the -validateCmd option (also go read that bit), the input gets additionally validated. double-checked, we love to see it. β¨
additionally, the Tcl extension code that implements this command hands you an API for adding C level coded handlers. up to now, the parser extension command that exists is "tdom". the handler set installed by this extension builds an in-memory "tDOM" DOM tree while the parser is parsing the input. main character energy fr fr π
and yes β you can register an arbitrary amount of different handler scripts and C level handlers for most of the events. when the event happens, they all get called in turn. the more the merrier π«Ά
π COMMAND OPTIONS π
-namespaceβ enables namespace parsing. you must use this option while you're creating the parser with theexpatorxml::parsercommand. you can't enable (nor disable) namespace parsing later with<parserobj> configure ....β so decide now, bestie, it's a commitment π-namespaceseparatorchar β this one only does anything if you use it together with the-namespaceoption. if given, it decides which character gets inserted between the namespace URI and the local name while an XML element name is being reported to a handler script. the default is the character':'. the value must be a one-character string less or equal to\u00FF, preferably a 7-bit ASCII character or the empty string. and if the value is the empty string (and also if the value is\x00) then the namespace URI and the local name get concatenated with no separator at all. glued together. iconic πΈ-finalboolean β tells the parser whether the document data you're about to present to the parse method is the final part of the document. a value of"0"means more data is expected. a value of"1"means nothing more is coming. the default value is"1".
if this option is set to "0" then the parser will not report certain errors if the XML data isn't well-formed at the end of input β think unclosed or unbalanced start or end tags. instead, some data may be saved by the parser until the next call to the parse method, which means the reporting of some of that data gets delayed. patience, babe β³
if this option is set to "1" then documents that aren't well-formed upon end of input will generate an error. periodt.
-validateCmd<tdom schema cmd> β this option expects the name of a tDOM schema command. if you give it one, then the input is also validated. and if the schema command hasn't set areportcmdthen the first validation error will stop further parsing (treated just like a well-formedness error). bye bye parsing π-baseurlurl β reports the base url of the document to the parser. that's it. little guy, big job.-fastcallboolean β by default this option is0(off). if it's on, then any handler installed by the-elementstartcommand,-elementendcommandand-characterdatacommandoptions from that moment on gets installed in a way where calling it has less overhead than usual. you can switch this option back and forth between callback handler (re-)installations as much as you want. β¨
but there are some requirements, bestie, and they are not optional. the handler proc has to be defined before it's used as a callback. if it isn't, then the callback just gets installed as usual. and the handler proc must not be removed or re-defined for as long as it's being used as a callback.
β οΈ if you do remove or re-define it anyway, the program will probably crash β but it may also execute arbitrary code. yeah. we're not joking. do not do this. π
also: the callback handler installed while this option is on will not be traced when you execute it.
-keepTextStartboolean β by default this option is0(off). if it's on, then the position information for the start of a text or CDATA node is kept across the collecting of the cdata pieces expat sometimes delivers. with this option on, the position information returned by the parser inside a-characterdatacommandproc will be correct β otherwise, it won't be. π
called in all other handler code, the parser always returns the correct position results, no matter what value this option has. it's off by default because it's rarely needed and turning it off saves a few cpu cycles this way. efficiency queen π
-elementstartcommandscript β specifies a Tcl command to associate with the start tag of an element. the actual command is this option followed by at least two arguments: the element type name and the attribute list.
the attribute list is a Tcl list made of name/value pairs, suitable for passing straight to the array set Tcl command.
example:
proc HandleStart {name attlist} {
puts stderr "Element start ==> $name has attributes $attlist"
}
$parser configure -elementstartcommand HandleStart
$parser parse {<test id="123"></test>}
this would result in the following command being invoked:
HandleStart text {id 123}
-elementendcommandscript β specifies a Tcl command to associate with the end tag of an element. the actual command is this option followed by at least one argument: the element type name. and on top of that, if the-reportemptyoption is set, then the command may be invoked with the-emptyconfiguration option to indicate whether it's an empty element. (peep the description of the-reportemptyoption for an example π)
example:
proc HandleEnd {name} {
puts stderr "Element end ==> $name"
}
$parser configure -elementendcommand HandleEnd
$parser parse {<test id="123"></test>}
this would result in the following command being invoked:
HandleEnd test
-characterdatacommandscript β specifies a Tcl command to associate with character data in the document, ie. text. the actual command is this option followed by one argument: the text.
and here's the glow-up: unlike with the C API of the expat parser, it is guaranteed that character data will be passed to the application in a single call to this command. one call, one text, no fragmenting π¦
example:
proc HandleText {data} {
puts stderr "Character data ==> $data"
}
$parser configure -characterdatacommand HandleText
$parser parse {<test>this is a test document</test>}
this would result in the following command being invoked:
HandleText {this is a test document}
-processinginstructioncommandscript β specifies a Tcl command to associate with processing instructions in the document. the actual command is this option followed by two arguments: the PI target and the PI data. π
example:
proc HandlePI {target data} {
puts stderr "Processing instruction ==> $target $data"
}
$parser configure -processinginstructioncommand HandlePI
$parser parse {<test><?special this is a processing instruction?></test>}
this would result in the following command being invoked:
HandlePI special {this is a processing instruction}
-notationdeclcommandscript β specifies a Tcl command to associate with notation declaration in the document. the actual command is this option followed by four arguments: the notation name, the base uri of the document (meaning: whatever was set by the-baseurloption), the system identifier and the public identifier. the notation name is never empty, but the other arguments may be. so check them, bestie π«Ά-externalentitycommandscript β specifies a Tcl command to associate with references to external entities in the document. the actual command is this option followed by three arguments: the base uri, the system identifier of the entity and the public identifier of the entity. the base uri and the public identifier may be the empty list.
this handler script has to return a Tcl list consisting of three elements. the first element of this list signals how the external entity is returned to the processor. at the moment, the three allowed types are "string", "channel" and "filename". the second element of the list has to be the (absolute) base URI of the external entity to be parsed. the third element of the list is the data β either the already-read data out of the external entity as a string, in the case of type "string", or the name of a Tcl channel, in the case of type "channel", or the path to the external entity to be read, in the case of type "filename". π
behind the scene, the external entity referenced by the returned Tcl channel, string or file name will be parsed with an expat external entity parser that has the same handler sets as the main parser. and if parsing of the external entity fails, the whole parsing gets stopped with an error message. π
also, if a Tcl command registered as externalentitycommand isn't able to resolve an external entity, it's allowed to return TCL_CONTINUE. in that case, the wrapper gives the next registered externalentitycommand a try. and if no externalentitycommand is able to handle it, the external entity parsing stops with an error.
Example:
proc externalEntityRefHandler {base systemId publicId} {
if {![regexp {^[a-zA-Z]+:/} $systemId]} {
regsub {^[a-zA-Z]+:} $base {} base
set basedir [file dirname $base]
set systemId "[set basedir]/[set systemId]"
} else {
regsub {^[a-zA-Z]+:} $systemId systemId
}
if {[catch {set fd [open $systemId]}]} {
return -code error \
-errorinfo "Failed to open external entity $systemId"
}
return [list channel $systemId $fd]
}
set parser [expat -externalentitycommand externalEntityRefHandler \
-baseurl "file:///local/doc/doc.xml" \
-paramentityparsing notstandalone]
$parser parse {<?xml version='1.0'?>
<!DOCTYPE test SYSTEM "test.dtd">
<test/>}
And bestie, that whole vibe ends up running this:
externalEntityRefHandler file:///local/doc/doc.xml test.dtd {}
External entities only get resolved through this handler script if it's actually necessary, okay? Meaning: external parameter entities only trigger this handler when -paramentityparsing is set with the argument always, or when -paramentityparsing is set with the argument notstandalone and the document isn't marked as standalone. That's the rule, no cap. π
-unknownencodingcommandscript β not implemented at Tcl level. That's it. That's the whole tea. π-startnamespacedeclcommandscript β sets a Tcl command to hook onto the start scope of namespace declarations in the document. The actual command it fires is this option followed by two arguments: the namespace prefix and the namespace URI. For anxmlnsattribute, the prefix will be the empty list. For anxmlns=""attribute, the uri will be the empty list. Also super important: the calls to the start and end element handlers happen between the calls to the start and end namespace declaration handlers. β¨-endnamespacedeclcommandscript β sets a Tcl command to hook onto the end scope of namespace declarations in the document. The actual command is this option followed by the namespace prefix as its argument. In the case of anxmlnsattribute, the prefix will be the empty list. And same as above: the start and end element handlers get called between the start and end namespace declaration handlers. π-commentcommandscript β sets a Tcl command to hook onto comments in the document. The actual command is this option followed by one argument: the comment data.
Example:
proc HandleComment {data} {
puts stderr "Comment ==> $data"
}
$parser configure -commentcommand HandleComment
$parser parse {<test><!-- this is <obviously> a comment --></test>}
This would result in the following command being invoked:
HandleComment { this is <obviously> a comment }
-notstandalonecommandscript β this Tcl command gets called when the document is not standalone (as in: it has an external subset or a reference to a parameter entity, but doesn't havestandalone="yes"). It's called with no additional arguments. Zero extra args, it just wants to chat. π«Ά-startcdatasectioncommandscript β sets a Tcl command to hook onto the start of a CDATA section. Called with no additional arguments.-endcdatasectioncommandscript β sets a Tcl command to hook onto the end of a CDATA section. Also called with no additional arguments. Symmetry, we love to see it. πΈ-elementdeclcommandscript β sets a Tcl command to hook onto element declarations. The actual command is this option followed by two arguments: the name of the element and the content model. The content model arg is a tcl list of four elements, and here's the breakdown because it's giving lore:- The first list element says what type of XML element it is; the six possible types get reported as
"MIXED","NAME","EMPTY","CHOICE","SEQ"or"ANY". - The second list element reports the quantifier for the content model in XML Syntax (
"?","*"or"+") or is the empty list. - If the type is
"MIXED", then the quantifier will be"{}"(meaning a PCDATA-only element), or"*"with the allowed elements to intermix with PCDATA as a tcl list as the fourth argument. - If the type is
"NAME", the name is the third arg; otherwise the third argument is the empty list. - If the type is
"CHOICE"or"SEQ", the fourth argument will contain a list of content models built exactly like this one. - The
"EMPTY","ANY", and"MIXED"types will only ever show up at top level.
- The first list element says what type of XML element it is; the six possible types get reported as
Examples:
proc elDeclHandler {name content} {
puts "$name $content"
}
set parser [expat -elementdeclcommand elDeclHandler]
$parser parse {<?xml version='1.0'?>
<!DOCTYPE test [
<!ELEMENT test (#PCDATA)>
]>
<test>foo</test>}
This would result in the following command being invoked:
test {MIXED {} {} {}}
$parser reset
$parser parse {<?xml version='1.0'?>
<!DOCTYPE test [
<!ELEMENT test (a|b)>
]>
<test><a/></test>}
This would result in the following command being invoked:
elDeclHandler test {CHOICE {} {} {{NAME {} a {}} {NAME {} b {}}}}
-attlistdeclcommandscript β sets a Tcl command to hook onto attlist declarations. The actual command is this option followed by five arguments. And heads up: the Attlist declaration handler gets called for each attribute, so a single Attlist declaration with multiple attributes declared will generate multiple calls to this handler. The arguments are: the element name this attribute belongs to, the name of the attribute, the type of the attribute, the default value (which may be the empty list) and a required flag. If that flag is true and the default value is not the empty list, then this is a"#FIXED"default.
Example:
proc attlistHandler {elname name type default isRequired} {
puts "$elname $name $type $default $isRequired"
}
set parser [expat -attlistdeclcommand attlistHandler]
$parser parse {<?xml version='1.0'?>
<!DOCTYPE test [
<!ELEMENT test EMPTY>
<!ATTLIST test
id ID #REQUIRED
name CDATA #IMPLIED>
]>
<test/>}
This would result in the following commands being invoked:
attlistHandler test id ID {} 1
attlistHandler test name CDATA {} 0
-startdoctypedeclcommandscript β sets a Tcl command to hook onto the start of the DOCTYPE declaration. This command is called before any DTD or internal subset is parsed. The actual command is this option followed by four arguments: the doctype name, the system identifier, the public identifier, and a boolean that shows whether the DOCTYPE has an internal subset. π¦-enddoctypedeclcommandscript β sets a Tcl command to hook onto the end of the DOCTYPE declaration. This one's called after processing any external subset. It's called with no additional arguments.-paramentityparsingnever|notstandalone|alwaysβneverdisables expansion of parameter entities,alwaysexpands always, andnotstandaloneexpands only if the document isn'tstandalone='no'. The default isnever. Periodt. π-entitydeclcommandscript β sets a Tcl command to hook onto any entity declaration. The actual command is this option followed by seven arguments: the entity name, a boolean identifying parameter entities, the value of the entity, the base uri, the system identifier, the public identifier and the notation name. Depending on the type of entity declaration, some of these arguments may be the empty list. (Yes, seven args. She's thorough. π)-ignorewhitecdataboolean β if this flag is set, element content that contains only whitespaces isn't reported with the-characterdatacommand.-ignorewhitespaceboolean β another name for-ignorewhitecdata; see there. Same energy, different spelling. β¨-handlersetname β this option sets the Tcl handler set scope for the configure options. Any option value pair following this option in the same call to the parser are modifying the named Tcl handler set. If you don't use this option, you're modifying the default Tcl handler set, which is named"default".-noexpandboolean β normally, the parser tries to expand references to entities defined in the internal subset. If this option is set to a true value, those entities are not expanded, but reported literal via the default handler.
β οΈ Warning bestie, listen: if you set this option to true and don't install a default handler (with the -defaultcommand option) for every handler set of the parser, all internal entities are silently lost for the handler sets without a default handler. Silently. Lost. Not a drill. π
-useForeignDTD<boolean>β if<boolean>is true and the document does not have an external subset, the parser will call the-externalentitycommandscript with empty values for thesystemIdandpublicIDarguments. This option must be set before the first piece of data is parsed. Setting this option after parsing has started has no effect β the vibe check already happened. The default is not to use a foreign DTD. That default is restored after resetting the parser. Please notice that a-paramentityparsingvalue of"never"(which is the default) suppresses any call to the-externalentitycommandscript. And please also notice that, if the document also doesn't have an internal subset, the-startdoctypedeclcommandandenddoctypedeclcommandscripts, if set, are not called. π₯
okay so, last two options in this section, and they're both about β¨protecting youβ¨ from chaos:
-billionLaughsAttackProtectionMaximumAmplification<float> β <URL: https://en.wikipedia.org/wiki/Billion_laughs_attack> this one, together with-billionLaughsAttackProtectionActivationThreshold, gives you control over the parser limits that protect against billion laugh attacks (). It expects a float>= 1.0as its argument. You should never need to use this option, because the default value (100.0) should work for any real data. If you ever do need to increase this value for non-attack payload, please report. π«Ά-billionLaughsAttackProtectionActivationThreshold<long> β <URL: https://en.wikipedia.org/wiki/Billion_laughs_attack> this one, together with-billionLaughsAttackProtectionMaximumAmplification, gives you control over the parser limits that protect against billion laugh attacks (). It expects a positive integer as its argument. Again, you should never need to use this option, because the default value (8388608) should work for any real data. If you ever do need to increase this value for non-attack payload, please report. π
π COMMAND METHODS π
parser configure option value ?option value?β sets configuration options for the parser. Every command option, except-namespace, can be set or modified with this method. slay. β¨parser cget ?-handlerset name? optionβ returns the current configuration value option for the parser. If the-handlersetoption is used, the configuration for the named handler set is returned. πparser currentmarkupβ returns the current markup as found in the XML, if called from within one of its markup event handler scripts (-elementstartcommand,-elementendcommand,-commentcommandand-processinginstructioncommand). Otherwise it returns the empty string. no cap.parser deleteβ deletes the parser and the parser command. β οΈ A parser cannot be deleted from within one of its handler callbacks (neither directly nor indirectly) and will raise a tcl error in this case. bestie don't try it. πparser freeβ another name to call the methoddelete, see there. same energy, different name. π¦parser getβ the option you pass here is one of-specifiedattributecount,-idattributeindex,-currentbytecount,-currentlinenumber,-currentcolumnnumber,-currentbyteindex:-specifiedattributecountβ returns the number of the attribute/value pairs passed in last call to theelementstartcommandthat were specified in the start-tag rather than defaulted. Each attribute/value pair counts as2; thus this corresponds to an index into the attribute list passed to theelementstartcommand. π’-idattributeindexβ returns the index of the ID attribute passed in the last call toXML_StartElementHandler, or-1if there is no ID attribute. Each attribute/value pair counts as2; thus this corresponds to an index into the attributes list passed to theelementstartcommand.-currentbytecountβ return the number of bytes in the current event. Returns0if the event is in an internal entity. If you use this option consider if you may need the parser option-keepTextStart. πΈ-currentlinenumberβ returns the line number of the current parse location. If you use this option consider if you may need the parser option-keepTextStart.-currentcolumnnumberβ returns the column number of the current parse location. If you use this option consider if you may need the parser option-keepTextStart.-currentbyteindexβ returns the byte index of the current parse location. If you use this option consider if you may need the parser option-keepTextStart.
Only one value may be requested at a time. periodt. π
parser parse dataβ parses the XML string data. The event callback scripts will be called, as their triggering events happen. This method cannot be used from within a callback (neither directly nor indirectly) of the parser to be used and will raise an error in this case.parser parsechannel channelIDβ reads the XML data out of the tcl channel channelID (starting at the current access position, without any seek) up to the end of file condition and parses that data. The channel encoding is respected. Use the helper proctDOM::xmlOpenFileout of the tDOM script library to open a file, if you want to use this method. This method cannot be used from within a callback (neither directly nor indirectly) of the parser to be used and will raise an error in this case. πparser parsefile filenameβ reads the XML data directly out of the file with the filename filename and parses that data. This is done with low-level file operations. The XML data must be inUS-ASCII,ISO-8859-1,UTF-8orUTF-16encoding. If applicable, this is the fastest way, to parse XML data. This method cannot be used from within a callback (neither directly nor indirectly) of the parser to be used and will raise an error in this case. β‘parser resetβ resets the parser in preparation for parsing another document. A parser cannot be reset from within one of its handler callbacks (neither directly nor indirectly) and will raise a tcl error in this cases. π
π Callback Command Return Codes π
A script invoked for any of the parser callback commands, such as -elementstartcommand, -elementendcommand, etc, may return an error code other than "ok" or "error". All callbacks may in addition return "break" or "continue". iconic behaviour honestly π
- If a callback script returns an
"error"error code then processing of the document is terminated and the error is propagated in the usual fashion. π - If a callback script returns a
"break"error code then all further processing of every handler script out of this Tcl handler set is suppressed for the further parsing. This does not influence any other handler set. β - If a callback script returns a
"continue"error code then processing of the current element, and its children, ceases for every handler script out of this Tcl handler set and processing continues with the next (sibling) element. This does not influence any other handler set. π - If a callback script returns a
"return"error code then parsing is canceled altogether, but no error is raised. sneaky but valid. π
π SEE ALSO π
expatapi, tdom β go read those next bestie, they're giving main character energy. π
β¨ KEYWORDS β¨
SAX, push, pushparser β iykyk. π
and that's a wrap on expat(n) from the Tcl crew π«Ά this whole page is brought to you by Tcl and expat(n), so go forth and parse responsibly, bestie. no cap, you ate. πβ¨ππ¦πΈ
π¦ where this page comes from
- fedora 43: tdom 0.9.6-3.fc43 Β· MPL-2.0 AND MIT
- fedora 44: tdom 0.9.6-3.fc44 Β· MPL-2.0 AND MIT
- nixos 26.05: tdom 0.9.6
- nixpkgs unstable: tdom 0.9.6
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms