R xpathApply:在使用xpathSApply时如何使用条件语句而不是循环?

时间:2015-03-13 10:50:23

标签: xml r xpath

我想知道在xpathSApply中使用R时是否有使用条件语句的选项。下面的例子工作正常,但我想有更有效的选择?

exemel<-'<?xml version="1.0" encoding="utf-8"?>
<Production  xmlns="http://www.w3.org/2001/XMLSchema-instance">
    <Item>
        <ItemNr>1</ItemNr>
        <Category>Processing</Category>
        <Processed>
            <Dia>325</Dia>
            <Log>
                <LogKey>1</LogKey>
            </Log>
            <Log>
                <LogKey>2</LogKey>
            </Log>
        </Processed>
    </Item>
    <Item>
        <ItemNr>2</ItemNr>
        <Category>NoProcessing</Category>
        <NotProcessed>
            <Dia>72</Dia>
        </NotProcessed>
    </Item>
    <Item>
        <ItemNr>3</ItemNr>
        <Category>Processing</Category>
        <Processed>
            <Dia>95</Dia>
            <Log>
                <LogKey>1</LogKey>
            </Log>
        </Processed>
    </Item>
</Production>'

xmlf <- xmlParse(exemel)
nsDefs <- xmlNamespaceDefinitions(xmlf, simplify=T)
ItemNumbers <- as.numeric(xpathSApply(xmlf, "//d:Item/d:ItemNr", xmlValue, namespaces=c(d=nsDefs[[1]])))

maxkeys=NULL
for (i in ItemNumbers) {  
  logkeys <- as.numeric(xpathSApply(xmlf, paste("//d:Item[d:ItemNr='", i, "']//d:LogKey", sep=""), 
                                    xmlValue, namespaces=c(d=nsDefs[[1]])))
  if (length(logkeys)>0) {
    maxkeys[i] = max(logkeys)
  } else {
    maxkeys[i]  = NA
  }  
}   
print(maxkeys)
#[1] 2 NA 1

那么,有没有选择使用条件语句代替这个循环?

1 个答案:

答案 0 :(得分:0)

定义getMaxLogKey以获得最大LogKey给定的Item节点,然后将其应用于所有项目:

library(XML)
xmlf <- xmlParse(exemel)

getMaxLogKey <- function(x) {
  LogKeys <- xpathSApply(x, ".//d:LogKey", xmlValue, namespaces = "d")
  if (length(LogKeys)) max(as.numeric(LogKeys)) else NA
}

xpathSApply(xmlf, "//d:Item", getMaxLogKey, namespaces = "d")

,并提供:

[1]  2 NA  1