[R] Basic editing of XML file

Ben Tupper btupper at bigelow.org
Thu Aug 13 16:08:35 CEST 2015


Hi,

Your email client is set to send in HTML format which has mangled your message.  Please set your client to send plain text to R-help.

You could use the XML package to modify the attributes of a given node.

> library(XML)

# make an reproducible example
> z <- newXMLNode("BLABLA",
+     attrs = c(version = "XXX"),
+     .children = list(
+         newXMLNode("A1", 
+             attrs = c(X1=2, X2="0", X3 = "100")),
+         newXMLNode("A2", 
+             attrs = c(X1=133.708, X2=36.28558)),
+         newXMLNode("A3",
+             attrs = c(X1=1, X2 = 2, X3 = 3, X4 = 4))
+         ))
> z
<BLABLA version="XXX">
  <A1 X1="2" X2="0" X3="100"/>
  <A2 X1="133.708" X2="36.28558"/>
  <A3 X1="1" X2="2" X3="3" X4="4"/>
</BLABLA> 

# XML child nodes can be access using like a list 
# z[['A1']] will extract the first node with that name
# then use the XML::xmlAttrs() function to get and set the attributes 
> a1_atts <- xmlAttrs(z[["A1"]])
> a1_atts
   X1    X2    X3 
  "2"   "0" "100" 
> a1_atts[['X3']] <- "boo"
> xmlAttrs(z[["A1"]]) <- a1_atts
> z
<BLABLA version="XXX">
  <A1 X1="2" X2="0" X3="boo"/>
  <A2 X1="133.708" X2="36.28558"/>
  <A3 X1="1" X2="2" X3="3" X4="4"/>
</BLABLA> 

Is that what you want to do?


Cheers,
Ben


On Aug 13, 2015, at 8:51 AM, Robert U <tacsunday at yahoo.fr> wrote:

> Dear RUser,I’m tryingto operate some very slight editing to the values of an XML file. I looked abit everywhere and it appears that dealing with XML files is not that easy… besidemy XML files might be a bit weirdly structured. Anyway, let me give you an exampleof it :
> Root(xmlfile)<BLABLA version="XXX">  <A1 X1="2" X2="0"X3="100">    <A2 X1="133.708" X2="36.28558"/>   <A3 X1="0" X2="0" X3="0" X4="0"/>   <A4 mode="0"/>    …  ………  </ A1 ></ BLABLA > I’d like to modify the value of say,X1 in A1 line, or X1 in A2 line. Unfortunately the structure of this datasetdoes not really look like the examples I’ve seen on the internet, where youhave something that look like that : <A1> something to change </A1> In my case as you noticed, thevalues I want to edit are inside de <>, which is pretty odd… Any tips?  Regards
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org



More information about the R-help mailing list