我需要從具有相同節點名稱但每個節點的屬性數量不同的 xml 檔案中提取某些屬性。該檔案位于此處:
https://boardgamegeek.com//xmlapi//boardgame//13&type=boardgame,boardgameexpansion,boardgameaccesory,rpgitem,rpgissue,videogame&versions=1&stats=1&videos=1&marketplace=1&comments=1&pricehistory=1
這是檔案本身的一小部分:
<boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
<boardgame objectid="13">
<yearpublished>1995</yearpublished>
<minplayers>3</minplayers>
<maxplayers>4</maxplayers>
<playingtime>120</playingtime>
<minplaytime>60</minplaytime>
<maxplaytime>120</maxplaytime>
<age>10</age>
<name sortindex="1">Catan</name>
<name primary="true" sortindex="1">CATAN</name>
<name sortindex="1">Catan (Колонизаторы)</name>
<name sortindex="1">Catan telepesei</name>
<name sortindex="1">Catan: Das Spiel</name>
<name sortindex="1">Catan: Die Bordspel</name>
<name sortindex="1">Catan: El Juego</name>
<name sortindex="1">Catan: Gra planszowa</name>
<name sortindex="1">Catan: Il Gioco</name>
<name sortindex="1">Catan: Landnemarnir</name>
我只想從每行中提取“sortindex”的值,并將“name”作為節點名稱。我嘗試了以下方法,但它回傳了第二個“名稱”節點的主“真”和排序索引值。我嘗試了很多不同的方法,但我無法讓它發揮作用。我試過 xmlGetAttr 和其他人。如何讓這個簡單的操作起作用?
data <- read_xml(url)
xmlfile <- xmlParse(data)
xmltop = xmlRoot(xmlfile)
xmlSApply(getNodeSet(xmltop, '//name[@sortindex]'), xmlAttrs)
> xmlSApply(getNodeSet(xmltop, '//name[@primary]'), xmlAttrs)
[,1]
primary "true"
sortindex "1"
uj5u.com熱心網友回復:
聽起來您想包含任何名稱節點,即使它沒有該屬性。如果是這樣,您可以嘗試以下方法:
data <- read_xml('https://boardgamegeek.com//xmlapi//boardgame//13&type=boardgame,boardgameexpansion,boardgameaccesory,rpgitem,rpgissue,videogame&versions=1&stats=1&videos=1&marketplace=1&comments=1&pricehistory=1')
xmlfile <- xmlParse(data)
xmltop <- xmlRoot(xmlfile)
getAttr <- function(x, attrName) {
attrs <- xmlAttrs(x)
if (attrName %in% names(attrs)) {
attrs[[attrName]]
} else {
NA
}
}
xmlSApply(getNodeSet(xmltop, '//name'), function(x)getAttr(x, "sortindex"))
xmlSApply(getNodeSet(xmltop, '//name'), function(x)getAttr(x, "primary"))
如果您不想包含沒有屬性的節點,那么您可以執行非常類似的操作:
library(xml2)
library(XML)
data <- read_xml('https://boardgamegeek.com//xmlapi//boardgame//13&type=boardgame,boardgameexpansion,boardgameaccesory,rpgitem,rpgissue,videogame&versions=1&stats=1&videos=1&marketplace=1&comments=1&pricehistory=1')
xmlfile <- xmlParse(data)
xmltop <- xmlRoot(xmlfile)
xmlSApply(getNodeSet(xmltop, '//name[@sortindex]'), function(x)xmlAttrs(x)[['sortindex']])
xmlSApply(getNodeSet(xmltop, '//name[@primary]'), function(x)xmlAttrs(x)[['primary']])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512766.html
標籤:rxmlxml2
