1

I have a XML, see sample below

<params>
<param id='1'>BEN</param>
<param id='2'>DAN</param>
<param id='3'>RYE</param>
    <param id='3'>RYE</param>
    <param id='3'>RYE</param>
</params>

How can I get all the param with attribute id=3?

Below is what I have done so far : xmlinfile is the XML file

inxml = xmlTreeParse(xmlinfile, handlers=list("comment"=function(x,...){NULL}), asTree = TRUE)
xmlList = xmlToList(inxml);
params = xmlList$'params'

Thanks ahead.

2 Answers 2

2

You need to use function xpathApply with argument xmlValue (to get the value, otherwise xmlAttrs to get the attribute). The path should be given in the following syntax :"//tag[@attribute='value']".

a <- xmlParse('<params>
<param id='1'>BEN</param>
<param id='2'>DAN</param>
<param id='3'>RYE</param>
    <param id='3'>RYE</param>
    <param id='3'>RYE</param>
</params>')
xpathApply(a,"//param[@id='3']",xmlValue)
[[1]]
[1] "RYE"

[[2]]
[1] "RYE"

[[3]]
[1] "RYE"

Similarly xpathSApply will gives you a vector of value when possible:

xpathSApply(a,"//param[@id='3']",xmlValue)
[1] "RYE" "RYE" "RYE"
Sign up to request clarification or add additional context in comments.

Comments

0
xmlinfile <- paste(readLines(n=7), collapse="\n")
<params>
  <param id='1'>BEN</param>
  <param id='2'>DAN</param>
  <param id='3'>RYE</param>
  <param id='3'>RYE</param>
  <param id='3'>RYE</param>
</params>
library(XML)
xpathApply(xmlParse(xmlinfile), "/params/param[@id='3']", xmlValue)  
# [[1]]
# [1] "RYE"
# 
# [[2]]
# [1] "RYE"
# 
# [[3]]
# [1] "RYE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.