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

Time:03-05

First, we identify if the attribute exists in nodes-of-interest

library(xml2)

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

First, we identify whether the ATTR_Z="index" attribute exists on the "root" node. If there is no add the new attribute between ATTR_B="test" and ATTR_C="test" ELSE keep xml .

I Tried:

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

It gives an error because the .after( ) does not exis. Any idea how to resolve this?

Expected Output:

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

CodePudding user response:

I am not sure there is an easy way to specify the position of a new attribute other than at the end.

In the code below I retrieve the list of attributes, strip all of the attributes from the root node and then replaced them with the new list. In the code below I added the new attribute first. The problem statement was not clear on whether the new attribute was alway the third position or the preceding attribute may vary in position.

See comments for the 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
  • Related