提取XML属性和节点值R [英] extract XML attributes and node values R
问题描述
我在R中有一个XML文件.该XML文件如下所示:
I have an XML file in R. The XML file looks like this:
rootNode <- xmlRoot(xmlfile)
rootNode[[1]]
<pdv id="1000001" latitude="4620114" longitude="519791" cp="01000" pop="R">
<adresse>ROUTE NATIONALE</adresse>
<ville>SAINT-DENIS-LèS-BOURG</ville>
<ouverture debut="01:00" fin="01:00" saufjour=""/>
<services>
<service>Automate CB</service>
<service>Vente de gaz domestique</service>
<service>Station de gonflage</service>
</services>
<prix nom="Gazole" id="1" maj="2014-01-02 11:08:03" valeur="1304"/>
<prix nom="SP98" id="6" maj="2014-12-31 08:39:46" valeur="1285"/>
<prix nom="Gazole" id="1" maj="2007-02-28 07:48:59.315736" valeur="999"/>
<fermeture/>
<rupture/>
</pdv>
rootNode [[2]]是:
the rootNode[[2]] is:
<pdv id="1000002" latitude="4621842" longitude="522767" cp="01000" pop="R">
<adresse>16 Avenue de Marboz</adresse>
<ville>BOURG-EN-BRESSE</ville>
<ouverture debut="08:45" fin="19:30" saufjour="Dimanche"/>
<services>
<service>Automate CB</service>
<service>Vente de gaz domestique</service>
<service>Station de gonflage</service>
</services>
<prix nom="Gazole" id="1" maj="2007-01-02 08:34:29.101626" valeur="995"/>
<prix nom="Gazole" id="1" maj="2007-01-26 09:49:39.197356" valeur="977"/>
<fermeture/>
<rupture/>
</pdv>
以此类推.
我正在运行下一个代码以获取有关评估者"的信息
I am running the next code to get the information about "valuer"
valeur = xpathApply(rootNode, "//prix", xmlGetAttr, "valeur")
valeur <- data.frame(matrix(unlist(valeur), byrow=T),stringsAsFactors=FALSE)
实际上,我正在获取值"的值,但问题是:我无法确定前三个值属于rootNode [[1]],而后两个值属于rootNode [[2]]等.
Actually, I am getting the values of "valuer", but the problem is: I can't identify that the three first values belong to rootNode[[1]] and the last two values belong to rootNode[[2]] and so on.
如何创建一个变量,该变量指示三个第一个值属于rootNode [[1]],另外两个属于rootNode [[2]]?或至少我该如何放置一个条件,该条件仅带给我属于rootNode [[1]]的值?
How can create a variable indicating that three first values belong to rootNode[[1]] and the other two to rootNode[[2]]? or at least how can I put a conditional that just bring me the values that belong to rootNode[[1]]?
推荐答案
这可能不是最优雅的解决方案,但这是我在遇到非常相似的问题后才想到的唯一解决方案.
This might not be the most elegant solution, but it's the only one I could come up with after struggling with a very similar problem.
这是一种将来自每个pdv节点的id作为属性添加到每个prix子节点的方法:
Here is a way to add the id from each pdv node as an attribute to each prix sub-node:
for (i in 1:xmlSize(rootNode)) {
id = xmlGetAttr(node = rootNode[[i]],
name = "id")
sapply(X = rootNode[[i]]["prix"],
fun = addAttributes,
id = id)
}
根据您的需要,您可以轻松地创建一个与以下两个值匹配的数据框:
Depending on your needs, you could then easily create a data frame that matches these two values:
data.frame (id = xpathSApply(rootNode, "//prix", xmlGetAttr, "id" ),
valeur = xpathSApply(rootNode, "//prix", xmlGetAttr, "valeur")
)
返回:
id valeur
1 1000001 1304
2 1000001 1285
3 1000001 999
4 1000002 995
5 1000002 977
这篇关于提取XML属性和节点值R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!