首先,我們確定該屬性是否存在于感興趣的節點中
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" ELSE 之間添加新屬性,請保留 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>
uj5u.com熱心網友回復:
我不確定是否有一種簡單的方法可以指定新屬性的位置,而不是在末尾。
在下面的代碼中,我檢索屬性串列,從根節點中洗掉所有屬性,然后用新串列替換它們。在下面的代碼中,我首先添加了新屬性。問題陳述不清楚新屬性是否始終位于第三位,或者前一個屬性的位置可能會有所不同。
請參閱分步注釋:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/437732.html
