Skip to contents

Create a xml_fragment() from a data.frame, in which each row is a set of xml elements (columns).

Usage

data_frag(df, row_tags = "row", .attr = NULL)

Arguments

df

data frame that will be stored as set of xml elements

row_tags

character the tag name that is used for each row. Note that this can be a single value or a vector of length equal to the number of rows in the data.frame.

.attr

optional data.frame with xml row attributes

Value

xml_fragment() object

Examples

persons <- data.frame(
  name = c("John Doe", "Jane Doe"),
  age = c(30, 25),
  stringsAsFactors = FALSE
)

df <- data_frag(persons, row_tag = "person")
print(df)
#> {xml_fragment (2)}
#> [1]<person>
#>   <name>John Doe</name>
#>   <age>30</age>
#> </person>
#> [2]<person>
#>   <name>Jane Doe</name>
#>   <age>25</age>
#> </person>
#> ...

# setting ids on rows
persons <- data.frame(
  name = c("John Doe", "Jane Doe"),
  age = c(30, 25),
  id = c("p1", "p2"),
  stringsAsFactors = FALSE
)

df <- data_frag(
  persons[1:2],
  row_tag = "person",
  .attr = persons[3]
)

print(df)
#> {xml_fragment (2)}
#> [1]<person id="p1">
#>   <name>John Doe</name>
#>   <age>30</age>
#> </person>
#> [2]<person id="p2">
#>   <name>Jane Doe</name>
#>   <age>25</age>
#> </person>
#> ...

# turning it into a document
doc <- xml_doc("study", id = "1") / frag(
  source = "homeless db",
  data = df
)

cat(as.character(doc))
#> <?xml version='1.0' encoding='UTF-8'?>
#>  <study id="1">
#>   <source>homeless db</source>
#>   <data>
#>     <person id="p1">
#>       <name>John Doe</name>
#>       <age>30</age>
#>     </person>
#>     <person id="p2">
#>       <name>Jane Doe</name>
#>       <age>25</age>
#>     </person>
#>   </data>
#> </study>