[R] [XML packages] how to get the sub-node according to the sub-node's attribute?

Chris Stubben stubben at lanl.gov
Fri Jul 12 19:01:29 CEST 2013


>My question is:
>Is there a function that can get the sub-node according to the sub-node's attribute ?
>like that,in the mtcar.xml ,there is sub-node as follow:
><record id="Lotus Europa">        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2</record>
>I want to get the specific sub-node according to the attribute "id="Lotus Europa".
>Is there a simple function in the xml package?


Just use xpathSApply with brackets to specify the specific id...

 doc <- xmlParse(system.file("exampleData", "mtcars.xml", package="XML"))

xpathSApply(doc, "//record[@id='Lotus Europa']", xmlValue)
[1] "        30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2"

#OR?
xpathSApply(doc, "//record[@id='Lotus Europa']")
getNodeSet(doc, "//record[@id='Lotus Europa']")

# And to list all Ids...

xpathSApply(doc, "//record", xmlGetAttr, "id")
 [1] "Mazda RX4"           "Mazda RX4 Wag"       "Datsun 710"   .....   

-- 

Chris Stubben

Los Alamos National Lab
Bioscience Division
MS M888
Los Alamos, NM 87545



More information about the R-help mailing list