XPath and namespace specification for XML documents with an explicit default namespace

后端 未结 3 798
深忆病人
深忆病人 2020-12-03 19:25

I\'m struggling to get the correct combination of an XPath expression and the namespace specification as required by package XML (argument namespaces) f

3条回答
  •  情书的邮戳
    2020-12-03 20:13

    I had a similar issue, but in my case I did not care about the namespace and would like a solution that ignored the namespace.

    Assume that we have the following XML in the variable myxml:

    
    Test
    
    
    

    In R we want to read this so we run:

    myxml <- '
    
      Test
    
    
    '
    myxmltop <- xmlParse(myxml)
    ns <- xmlNamespaceDefinitions(myxmltop, simplify =  TRUE)
    

    Here I have simplified Rappster's code by using the simplify=TRUE parameter. Now we can add the name/prefix of the namespace as in Rappster's code:

    names(ns)[1] <- "xmlns"
    

    Now we can refer to this namespace by:

    getNodeSet(myxmltop, "//xmlns:Parameter", namespaces =ns)
    

    Simpler solution (ignoring namespaces)

    We can also be more flexible by matching on any namespace by doing:

    myxmltop <- xmlParse(myxml)
    getNodeSet(myxmltop, "//*[local-name() = 'Parameter']")
    

    This solution was inspired by this SO answer.

提交回复
热议问题