Created
January 27, 2025 19:27
-
-
Save dlebauer/bcf99b3ab47e20075ce9617b6ba0253d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(xml2) | |
library(yaml) | |
# note: does not handle XML attributes or namespaces. | |
# should work for simple xml structure used by PEcAn | |
# Convert XML to YAML | |
xml2yml <- function(xml_string) { | |
yaml_string <- xml_string |> | |
read_xml() |> | |
as_list() |> | |
as.yaml() | |
return(yaml_string) | |
} | |
# Convert YAML to XML | |
yml2xml <- function(yaml_string) { | |
xml_string <- yaml_string |> | |
yaml.load() |> | |
as_xml_document() |> | |
as.character() | |
return(xml_string) | |
} | |
# Examples | |
## xml2yml | |
xml_example <- ' | |
<pecan> | |
<outdir>/tmp/</outdir> | |
<pfts> | |
<pft> | |
<name>biocro.salix</name> | |
</pft> | |
</pfts> | |
<meta.analysis> | |
<iter>3000</iter> | |
</meta.analysis> | |
<ensemble> | |
<size>1</size> | |
<variable>StemBiom</variable> | |
</ensemble> | |
<model> | |
<name>BIOCRO</name> | |
</model> | |
<run> | |
<site> | |
<id>288</id> | |
<name>Sapelo Island</name> | |
</site> | |
<start.date>2004-01-01 06:00:00</start.date> | |
<end.date>2005-12-31 05:59:00</end.date> | |
<host> | |
<name>localhost</name> | |
</host> | |
</run> | |
</pecan>' | |
# Convert XML to YAML | |
yaml_result <- xml2yml(xml_example) | |
cat("YAML Output:\n", yaml_result) | |
## yml2xml | |
yaml_example <- ' | |
pecan: | |
outdir: /tmp/ | |
pfts: | |
pft: | |
name: biocro.salix | |
meta.analysis: | |
iter: 3000 | |
ensemble: | |
size: 1 | |
variable: StemBiom | |
model: | |
name: BIOCRO | |
run: | |
site: | |
id: 288 | |
name: Sapelo Island | |
start.date: 2004-01-01 06:00:00 | |
end.date: 2005-12-31 05:59:00 | |
host: | |
name: localhost' | |
# Convert back to XML | |
xml_result <- yml2xml(yaml_example) | |
cat("\nReconstructed XML:\n", xml_result) | |
# Tests | |
xml_result == xml_example |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment