简体   繁体   中英

Namespace without prefix in XML in R

In the XML package in R, it is possible to create a new xmlTree object with a namespace, eg using:

library(XML)
d = xmlTree("foo", namespaces = list(prefix = "url"))
d$doc()
# <?xml version="1.0"?>
# <foo xmlns:prefix="url"/>

How do I create a default namespace, without the prefix bar , such that it looks like the following?

# <?xml version="1.0"?>
# <foo xmlns="url"/>

The following does not produce what I expected.

library(XML)
d = xmlTree("foo", namespaces = list("url"))
d$doc()
# <?xml version="1.0"?>
# <url:foo xmlns:url="<dummy>"/>

There seems to be a difference between nameless lists and lists with an empty name in R.

1 - A nameless list:

list("url")
# [[1]]
# [1] "url"
names(list("url"))
# NULL

2 - A named list:

list(prefix = "url")
# $prefix
# [1] "url"
names(list(prefix = "url"))
# [1] "prefix"

3 - An incorrectly initialised empty-name list:

list("" = "url")
# Error: attempt to use zero-length variable name

4 - An hacky way to initialise an empty-name list:

setNames(list(prefix = "url"), "")
# [[1]]
# [1] "url"
names(setNames(list(prefix = "url"), ""))
# [1] ""

It would seem 1. and 4. are identical, however, in the package XML they produce different results. The first gives the incorrect XML as mentioned in the OP, whereas option 4. produces:

library(XML)
d = d = xmlTree("foo", namespaces = setNames(list(prefix = "url"), ""))
d$doc() 
# <?xml version="1.0"?>
# <foo xmlns="url"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM