Learn R Programming

xmlwriter (version 0.1.1)

xmlbuilder: Create a fast feed-forward XML builder

Description

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.

Usage

xmlbuilder(
  allow_fragments = TRUE,
  use_prolog = !allow_fragments,
  strict = FALSE
)

Value

An object of class `xmlbuilder

Arguments

allow_fragments

logical. Should a warning be issued if the XML document has multiple root elements? Set to FALSE to suppress when creating multiple xml fragments.

use_prolog

logical. Should the XML prolog be included in the output? Default is TRUE, which generate an UTF-8 xml prolog. Set to FALSE if you want to generate an xml fragment or manually prepend the prolog.

strict

logical. Should the builder check for dangling nodes, default is FALSE.

Details

  • $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.

Examples

Run this code
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

Run the code above in your browser using DataLab