The XML file used here is the data set provided by Casos Company.xml
First parse the XML file and intercept an XML code
1 <dynamicnetwork> 2 <metanetwork> 3 <nodes> 4 <Nodeclasstype= "Agent"ID= "Agent"> 5 <nodeID= "LDR"title= "Project Manager" /> 6 <nodeID= "Mgr1"title= "Art Director" /> 7 </Nodeclass> 8 <Nodeclasstype= "task"ID= "task"> 9 <nodeID= "T1"title= "Project Management" /> Ten <nodeID= "T2"title= "Administration" /> One </Nodeclass> A </nodes> - <Networks> - <Networksourcetype= "Agent"TargetType= "Agent"ID= "Agent x Agent"> the <LinkSource= "LDR"Target= "Mgr1"type= "Double"value= "1.0000" /> - <LinkSource= "LDR"Target= "MGR2"type= "Double"value= "1.0000" /> - </Network> - </dynamicnetwork> + </metanetwork>
View Code
As you can see, there are two categories of nodes and network under the root node, which need to extract the attribute values of the ID and title under the nodes node, the values of source and target under the network node, and determine the attributes to be used to make up the CSV file. Begins processing the XML file.
① first loads the XML package in R and reads the XML file
# Load the package required to read XML files.library ("xml"), # Also Load the other required Package.library ("methods"); # G Ive the input file name to the Function.xmlfile <-xmlparse (file= "Company.xml")
② find the root node and determine which node the desired attribute value is
# Get the node directory of the Id=agent class #xmltop[[1]][[1]][[1]]# get Id=knowledge Class of node directory #xmltop[[1]][[1]][[2]]# get Id=task Class of Node directory # XMLTOP[[1]][[1]][[3]] #得到id =agent x Agent Class network directory #xmltop[[1]][[2]][[1]] #得到id =agent x Knowledge class of network directory #xmltop [[1]] [[2]] [[2]] #得到id =agent x task Class network directory #xmltop[[1]][[2]][[3]]
③ Initializes a vector, stores the value of the ID, and, at the end, makes a data frame of several vectors datafram to construct the GetNode function to get the id attribute value of node
I wrote a repeat loop because I didn't find the related function in R.
Getnodeid <-Function (index) { #初始化向量nodes_id_temp, stores the ID value of the node obtained under the current parameter nodes_id_temp <-vector () # Initialize i i<-1 #获得当前节点总数 n <-xmlsize (Xmltop[[1]][[1]][[index]]) repeat{ temp=xmlgetattr ( Xmltop[[1]][[1]][[index]][[i]],name= "id") nodes_id_temp[i] <-temp #print (nodes_id_temp[i]) I <-i+1 if (i > N) break ; } nodes_id <<-C (nodes_id,nodes_id_temp)}
Convert XML to CSV using the R language