在 R 中使用 xpath 更新节点(未知深度)? [英] update a node (of unknown depth) using xpath in R?

查看:24
本文介绍了在 R 中使用 xpath 更新节点(未知深度)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像这样的 XMLNode 对象:

<a>1</a><b><c>1</c><d>2</d></b></foo>

(可用作 dput 转储:https://gist.github.com/4273470)

在不知道c"节点的嵌套性的情况下,如何将其值从1"更改为2"?我一直在玩 XML 包,但它不是很清楚 - 大多数示例似乎处理提取而不是更新信息.

我也尝试过使用 xmlToList,但后来我也不知道如何识别/更新任意深度列表上的节点.

解决方案

这里有一个两步法.(test 是您包含的 dput 输出).

找到$c

的路径

<代码>>xmlApply(测试,名称)$a文本文本"$bcd"c" "d"

知道路径后替换$c

xmlChildren(test[["b"]][["c"]]) <- "2"

If I have an XMLNode object that looks like this:

<foo>
 <a>1</a>
 <b>
  <c>1</c>
  <d>2</d>
 </b>
</foo>

(available as dput dump: https://gist.github.com/4273470)

without knowing the nestedness of the "c" node, how can I change its value from "1" to "2"? I have been playing with the XML package, but it is not terribly clear - most examples appear to deal with extracting rather than updating information.

I have also tried using xmlToList, but then I don't know how to identify / update a node on a list of arbitrary depth either.

解决方案

Here's a two-step method. (test is the dput output you included).

Find the path to $c

> xmlApply(test,names)
$a
  text 
"text" 

$b
  c   d 
"c" "d" 

Replace $c once you know the path

xmlChildren(test[["b"]][["c"]]) <- "2"

这篇关于在 R 中使用 xpath 更新节点(未知深度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆