0

R で XML パッケージを使用して操作しようとしている次の XML ファイルtest.graphmlがあります。

<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
     http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault="directed">
    <node id="n0"/>
    <node id="n1"/>
    <node id="n2"/>
    <node id="n3"/>
    <node id="n4"/>
    <edge source="n0" target="n1"/>
    <edge source="n0" target="n2"/>
    <edge source="n2" target="n3"/>
    <edge source="n1" target="n3"/>
    <edge source="n3" target="n4"/>
  </graph>
</graphml>

以下に示すように、ノード n0、n1、n2、および n3 を新しいグラフ ノードにネストしたいと考えています。

<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
     http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault="directed">
    <graph id="g1">
       <node id="n0"/>
       <node id="n1"/>
       <node id="n2"/>
       <node id="n3"/>
    </graph>
    <node id="n4"/>
    <edge source="n0" target="n1"/>
    <edge source="n0" target="n2"/>
    <edge source="n2" target="n3"/>
    <edge source="n1" target="n3"/>
    <edge source="n3" target="n4"/>
  </graph>
</graphml>

私が書いたコードには、XML 処理の経験がないために解決できない不明な点やエラーがあります。先に進むのに役立ついくつかの指針をいただければ幸いです。

library(XML)

# Read file
x <- xmlParse("test.graphml")
ns <- c(graphml ="http://graphml.graphdrawing.org/xmlns")

# Create new graph node
ng <- xmlNode("graph", attrs = c("id" = "g1"))

# Add n0-n3 as children of new graph node 
n0_n1_n2_n3 <- getNodeSet(x,"//graphml:node[@id = 'n0' or @id='n1' or @id='n2' or @id='n3']", namespaces = ns)
ng <- append.xmlNode(ng, n0_n1_n2_n3)

# Get only graph node
g <- getNodeSet(x,"//graphml:graph", namespaces = ns)

# Remove nodes n0-n3 from the only graph node
# How I do this?
# This did not work: removeNodes(g, n0_n1_n2_n3)

# Add new graph node as child of only graph node    
g <- append.xmlNode(g, ng)
  #! Error message:
  Error in UseMethod("append") : 
  no applicable method for 'append' applied to an object of class "XMLNodeSet"
4

1 に答える 1