使用 xml2 更改 XML 文件中的值

Change Value in XML File using xml2

我得到了一个 .xml 文件,看起来像这样

<document>
<attribute1>false</attribute1>
<subjects>
    <subject>
        <population>Adult</population>
        <name>adult1</name>
    </subject>
</subjects>
</document>

我想将 <name> 的值更改为“adult5”。

我正在使用 xml2 包。 使用 XMLFile <- read_xml(path_xml) 我读取了 xml 文件,使用 xml_children(xml_children(xml_children(XMLFile)[2])[[1]])[2] 我可以访问节点和 R 在控制台上提示“adult1”。

但如果我尝试 xml_replace(xml_children(xml_children(xml_children(XMLFile)[2])[[1]])[2], "<name>adult5</name>"),结果会是 <<name>adult#005</name>/>

可能是我在这里遗漏的一个非常愚蠢的错误...

提前致谢!

您可以简单地select您想要的节点,然后使用xml_text(node) <- "new text"覆盖该节点。您不需要放入标签等 - 这就是使用 xml 包的全部意义所在。您的案例的一个有效示例可能是:

文件:my_xml.xml

<?xml version="1.0" encoding="UTF-8"?>
<document>
  <attribute1>false</attribute1>
  <subjects>
    <subject>
      <population>Adult</population>
      <name>adult1</name>
    </subject>
  </subjects>
</document>

现在在 R 中:

library(xml2)

XMLFile <- read_xml("my_xml.xml")

# Identify the node you want to change:
my_node <- xml_find_first(XMLFile, xpath = "//name")
xml_text(my_node)
#> [1] "adult1"

# Write to the node
xml_text(my_node) <- "adult5"

# Test the change has been made
xml_text(my_node)
#> [1] "adult5"

# Save the file
write_xml(XMLFile, "my_xml2.xml")

现在当我们查看 my_xml2.xml 时,我们的更改已保存:

文件:my_xml2.xml

<?xml version="1.0" encoding="UTF-8"?>
<document>
  <attribute1>false</attribute1>
  <subjects>
    <subject>
      <population>Adult</population>
      <name>adult5</name>
    </subject>
  </subjects>
</document>