如何在R语言中提取XML文件name节点的sortindex属性
从XML中提取指定节点的特定属性
我需要从一个XML文件中提取所有name节点的sortindex属性值,该XML里存在节点名称相同但属性数量不同的情况(有的name节点同时有primary和sortindex属性,有的只有sortindex)。文件片段如下:
<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>
我尝试了以下R代码,但部分节点会同时返回primary和sortindex属性,用xmlGetAttr也没解决,请问怎么实现只提取sortindex?
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"
解决方案
问题出在你使用的xmlAttrs会返回节点的所有属性。要只提取sortindex,直接在xmlSApply中调用xmlGetAttr并指定目标属性名即可:
# 获取所有包含sortindex属性的name节点 name_nodes <- getNodeSet(xmltop, '//name[@sortindex]') # 提取每个节点的sortindex属性值 sortindex_values <- xmlSApply(name_nodes, function(node) xmlGetAttr(node, "sortindex"))
或者更简洁的写法:
sortindex_values <- xmlSApply(getNodeSet(xmltop, '//name[@sortindex]'), xmlGetAttr, "sortindex")
这样就能得到所有name节点的sortindex属性值,不会混入其他属性。
内容的提问来源于stack exchange,提问作者user8229029
相关产品推荐
相关产品推荐

