如何在 R 中使用 xml2 在两个现有属性之间设置新属性?

How to use xml2 in R to set new attribute between two existing attributes?

首先,我们确定属性是否存在于感兴趣的节点中

library(xml2)

x <- read_xml("<root ATTR_A="word" ATTR_B="test" ATTR_C="number"> <child id ='a'/> <child id='b' d='b'/> </root>")

首先,我们确定ATTR_Z="index" 属性是否存在于“根”节点上。如果 ATTR_B="test" 和 ATTR_C="test" 之间没有添加新属性,否则保留 xml .

我试过:

x <- xml_attr(x, ATTR_Z=,.after = ATTR_B ) <- "index"

它给出了一个错误,因为 .after( ) 不存在。知道如何解决这个问题吗?

预期输出:

<root ATTR_A="word" ATTR_B="test" ATTR_Z="index" ATTR_C="number"> <child id ='a'/> <child id='b' d='b'/> </root>

除了在末尾之外,我不确定是否有一种简单的方法来指定新属性的位置。

在下面的代码中,我检索了属性列表,从根节点中删除所有属性,然后用新列表替换它们。在下面的代码中,我首先添加了新属性。问题陈述不清楚新属性是否总是第三个位置或前面的属性可能位置不同。

查看 step-by-step 的评论:

library(xml2)

x <- read_xml("<root ATTR_A='word' ATTR_B='test' ATTR_C='number'> 
              <child id ='a'/> 
              <child id='b' d='b'/> 
              </root>")

#Find node to modify the attributes
rootnode <- xml_find_first(x, "//root")
#adds single attribtute at end
#xml_attr(rootnode, "ATTR_Z") <- "index"

x  #display
#get existing attributes
attrs<- xml_attrs(rootnode)
#named vector of attributes in the desired order
newattrs <-c(ATTR_Z="index", attrs)

#set a series of attributes
#Remove all attributes
xml_set_attrs(rootnode, c(NULL))
x  #display

#Install all attributes
xml_set_attrs(rootnode, newattrs)
x #display