何亮
2013-Jul-12 01:40 UTC
[R] [XML packages] how to get the sub-node according to the sub-node's attribute?
For example fileName <- system.file("exampleData", "mtcars.xml", package="XML") doc <- xmlTreeParse(fileName) r<-xmlRoot(doc) record<-r[["record"]] record the result : <record id="Mazda RX4">21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4</record> but in the mecars.xml there are 32 sub-nodes called "record" when I use xmlChildren function c<-xmlChildren(r)[["record"]] c is also like that <record id="Mazda RX4">21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4</record> just the first sub-node is the default 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? -- ºÎÁÁ Öйú¿ÆѧԺ´óѧ µØÀí¿ÆѧÓë×ÊÔ´Ñо¿Ëù ½µØˮѻ·ÓëµØ±í¹ý³ÌÖصãʵÑéÊÒ ±±¾©ÊÐ ³¯ÑôÇø ´óÍÍ·¼×11ºÅ µç»°£º13651318417 Liang He Institute of Geographic Sciences and Natural resource research Chinese Academy of Science, No.11, Datun Road, Chaoyang District, Beijing 100101, China Email: xhl860728@163.com Tel: +86(10) 6488 9513 Mob:+86 0 13651318417 [[alternative HTML version deleted]]
Chris Stubben
2013-Jul-12 17:01 UTC
[R] [XML packages] how to get the sub-node according to the sub-node's attribute?
>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