如何使用R替换XML节点

时间:2017-08-13 21:49:21

标签: r xml

我正在使用包" XML"在R。

中创建XML文件

这是我的R代码。

library(XML)
xmlWARN <- xmlParse(strWarningXMLFileName)
xmlWARN <- xmlRoot(xmlWARN)
newXMLNode("StartDateTime", format(min(MyData$timestamp),"%m/%d/%Y %H:%M"), parent = xmlWARN)       
newXMLNode("EndDateTime", format(max(MyData$timestamp),"%m/%d/%Y %H:%M"), parent = xmlWARN)
newXMLNode("Granularity", strGranularity, parent = xmlWARN)
newXMLNode("TimeGapInData",blnTimeSlotGaps , parent = xmlWARN)
newXMLNode("TimeGapInDataIntervals",intNumberOfMissingTimeslots , parent = xmlWARN)
newXMLNode("IncompleteTimespan",blnIncompleteTimeSpan , parent = xmlWARN)
saveXML(xmlWARN, strWarningXMLFileName)

这样可以在下面创建我的XML文件。

<Server-Block>
  <Platform>LINUX</Platform>
  <ServerName>MyServer</ServerName>
  <StartDateTime>08/12/2017 00:00</StartDateTime>
  <EndDateTime>08/12/2017 11:00</EndDateTime>
  <Granularity>1-minute</Granularity>
  <TimeGapInData>FALSE</TimeGapInData>
  <TimeGapInDataIntervals>0</TimeGapInDataIntervals>
  <IncompleteTimespan>FALSE</IncompleteTimespan>
  <AtLeastOneThresholdExceeded>TRUE</AtLeastOneThresholdExceeded>
  <LinuxCPUUtilizationPercentCollected>TRUE</LinuxCPUUtilizationPercentCollected>
  <LinuxCPUUtilizationPercentWithoutWIOThresholdMaximum>80</LinuxCPUUtilizationPercentWithoutWIOThresholdMaximum>
  <LinuxCPUUtilizationPercentWithoutWIOThresholdMaximumExceeded>TRUE</LinuxCPUUtilizationPercentWithoutWIOThresholdMaximumExceeded>
  <LinuxCPUUtilizationPercentWithoutWIOThresholdMaximumReached>98.887</LinuxCPUUtilizationPercentWithoutWIOThresholdMaximumReached>
  <LinuxCPUUtilizationPercentWithoutWIOThresholdAverageReached>9.04793040847201</LinuxCPUUtilizationPercentWithoutWIOThresholdAverageReached>
  <LinuxCPUUtilizationPercentWithoutWIOThresholdMaximumReachedCount>25</LinuxCPUUtilizationPercentWithoutWIOThresholdMaximumReachedCount>
  <StartDateTime>08/12/2017 00:00</StartDateTime>
  <EndDateTime>08/12/2017 11:00</EndDateTime>
  <Granularity>1-minute</Granularity>
  <TimeGapInData>FALSE</TimeGapInData>
  <TimeGapInDataIntervals>0</TimeGapInDataIntervals>
  <IncompleteTimespan>FALSE</IncompleteTimespan>
</Server-Block>

我唯一想知道的是如何替换节点的值。

例如改变:

<ServerName>MyServer</ServerName>

<ServerName>YourServer</ServerName>

任何建议都将受到赞赏。

谢谢,

1 个答案:

答案 0 :(得分:1)

希望这有帮助!

library(XML)
#test.xml is the xml file where you want to make changes
xml_doc = xmlParseDoc("test.xml")
#replace the value of 'ServerName' node
invisible(replaceNodes(xml_doc[["//Server-Block//ServerName/text()"]], newXMLTextNode("YourServer")))
xml_doc


如果它解决了您的问题,请不要忘记告诉我们:)

相关问题