我有一個帶有 USER_DEFINED 引數的 XML 檔案,我正試圖決議它。這是 XML 檔案的示例。
<userDefinedParameters>
<USER_DEFINED parameter="P1">LEFT</USER_DEFINED>
<USER_DEFINED parameter="P2">RIGHT</USER_DEFINED>
<USER_DEFINED parameter="P3">1234</USER_DEFINED>
<USER_DEFINED parameter="P4">5678</USER_DEFINED>
</userDefinedParameters>
</data>
</segment>
</body>
</head>
我能夠使用XML包和xpathApply. 但是,我無法以這種方式提取 USER_DEFINED 引數值。
由于 XML 中有幾條記錄,我想獲取所有 P1、P2 等,因為我使用xpathApply. 該檔案指出所有 USER_DEFINED 引數都作為“引數”和“值”,所以我想我需要拉為c('paramater', 'value')但我不知道如何使用 XML 來做到這一點。
我看過這個 SO page,它有很大幫助,但沒有回答這個問題。
感謝您的任何/所有幫助。
更新所需的輸出以及我如何嘗試獲取資料。請注意,以下代碼無法正常作業。
當前xpathApply用法獲取該userDefinedParameters部分中的所有 USER_DEFINED 行。如果我更改為,xpathApply(data, "//USER_DEFINED"), xmlValue)我將獲得所有值,但與引數名稱無關。我需要類似的東西,xpathApply(data, "//USER_DEFINED/P1"), xmlValue)但顯然,這行不通。
Library(XML)
fileName <- "./file.xml"
data <- xmlParse(fileName)
xml_data <- xmlToList(data)
p1 <- xpathApply(data, "//USER_DEFINED")
p2 <- xpathApply(data, "//USER_DEFINED")
# View(p1)
# "P1"
# LEFT
# LEFT
# RIGHT
# View(p2)
# "P2"
# RIGHT
# RIGHT
# LEFT
# ...
uj5u.com熱心網友回復:
如果你喜歡堅持使用 XML 包,你可以使用xmlAttrs里面的函式sapply
text <-' <head> <body> <segment>
<data>
<userDefinedParameters>
<USER_DEFINED parameter="P1">LEFT</USER_DEFINED>
<USER_DEFINED parameter="P2">right</USER_DEFINED>
<USER_DEFINED parameter="P3">1234</USER_DEFINED>
<USER_DEFINED parameter="P4">5678</USER_DEFINED>
</userDefinedParameters>
</data>
</segment>
</body>
</head>'
library(XML)
#read the document
doc <- xmlRoot(xmlParse(text))
#parse out the USER Defined nodes
# in this example there are 4 nodes
nodes<-xpathApply(doc, ".//userDefinedParameters/USER_DEFINED")
#step through each of the found nodes
# xmlAttrs is not a vectorized function thus requiring a loop
attributes <- sapply(nodes, function(n) {
#extract the attribute from each node
# if there was more than 1 attribute this will need updating
xmlAttrs(unlist(n)) })
#get values from each node
values<-xmlValue(nodes)
data.frame(attributes, values)
# attributes values
# 1 P1 LEFT
# 2 P2 right
# 3 P3 1234
# 4 P4 5678
uj5u.com熱心網友回復:
使用該xml2庫,您可以從節點獲取值以parameter使用xml_attr().
像這樣的東西:
library(xml2)
x <- read_xml('<userDefinedParameters>
<USER_DEFINED parameter="P1">LEFT</USER_DEFINED>
<USER_DEFINED parameter="P2">right</USER_DEFINED>
<USER_DEFINED parameter="P3">1234</USER_DEFINED>
<USER_DEFINED parameter="P4">5678</USER_DEFINED>
</userDefinedParameters>')
dataset <- data.frame(user_defined = x %>%
xml_find_all("//USER_DEFINED") %>%
xml_text(),
parameter = x %>%
xml_find_all("//USER_DEFINED") %>%
xml_attr("parameter"))
結果dataset:
user_defined parameter
1 LEFT P1
2 right P2
3 1234 P3
4 5678 P4
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370722.html
