xmlbuilder | R Documentation |
This function creates an XML builder that allows you to create XML documents in a feed-forward manner.
xmlbuilder
returns an object that has methods to create XML elements, text nodes, comments, and more.
xmlbuilder(
allow_fragments = TRUE,
use_prolog = !allow_fragments,
strict = FALSE
)
allow_fragments |
logical. Should a warning be issued if the XML document has multiple root elements?
Set to |
use_prolog |
logical. Should the XML prolog be included in the output?
Default is |
strict |
logical. Should the builder check for dangling nodes, default is |
$start(tag, ...)
(or $start_element
) starts an element with a given tag and attributes.
$end()
(or $end_element
) ends the current element.
$element(tag, text, ...)
creates an element with a given tag, text, and attributes.
$text(text)
creates a text node.
$fragment(..., .attr)
writes an xml fragment to the.
$comment(comment)
creates a comment node.
$to_xml_string()
returns the XML document or fragments(s) as a character vector.
An object of class 'xmlbuilder
b <-xmlbuilder()
b$start("root")
b$element("child1", "text1", attr1 = "value1")
b$element("child2", "text2", attr2 = "value2")
b$start("child3", attr3 = "value3")
b$text("text3")
b$element("child4", "text3", attr4 = "value4")
b$end("child3")
b$end("root")
print(b)
if (require("xml2")) {
# a builder can be converted to an xml_document using
doc <- as_xml_document(b)
# or equivalentlty
doc <-
b$to_xml_string() |>
read_xml()
}
# build some xml fragments
fms <- xmlbuilder(allow_fragments = TRUE)
fms$start("person", id = "1")
fms$element("name", "John Doe")
fms$element("age", 30)
fms$end("person")
fms$start("person", id = "2")
fms$element("name", "Jane Doe")
fms$element("age", 25)
fms$end("person")
fms$start("person", id = "3")
fms$element("name", "Jim Doe")
fms$element("age", 35)
fms$end("person")
s <- fms$to_xml_string()
as.character(fms)
length(s) # three fragments
# print xml string of the second fragment
print(s[2])
if (require("xml2")){
# convert to xml_nodes
nodes <- fms$to_xml_node_list()
length(nodes) # three nodes
# show the second xml_node
print(nodes[[2]])
}
# use fragments
xb <- xmlbuilder()
xb$start("study")
xb$fragment(
person = frag(
name = "John Doe",
age = 30
),
person = frag(
name = "Jane Doe",
age = 25
)
)
xb$end("study")
xb
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.