代码之家  ›  专栏  ›  技术社区  ›  Science11

使用xmlValue替换XML元素中的数字

r xml
  •  1
  • Science11  · 技术社区  · 10 年前

    我有很多数字

    preKId_2015 = c(242938L, 339402L, 361888L, 428033L, 442546L, 309790L, 355662L, 
    458179L, 465105L, 490383L, 524644L, 526614L, 539453L, 555516L, 
    569709L)
    

    我有一个xml文件,元素之间已经有一些其他id值

    <input-id> 
    "PreKId"
    12344 
    33433
    23343
    93893
    23333
    </input-id>
    

    我试图用2015年前KId_。我试过了

     doc <- xmlParseDoc("C:/... ProjectKids/test12.xml")
     nodes <- getNodeSet(doc, "//input-id")[[1]]
     xmlValue(nodes) =  replace(xmlValue(nodes),xmlValue(nodes),preKId_2015)
    

    我收到警告,但什么都没发生

     Warning message:
     In replace(xmlValue(nodes), xmlValue(nodes),preKId_2015) :
       number of items to replace is not a multiple of replacement length
    

    需要帮助

    1 回复  |  直到 10 年前
        1
  •  1
  •   bergant    10 年前

    尝试使用 removeChildren 插入新节点之前:

    doc <- xmlParseDoc("C:/... ProjectKids/test12.xml")
    nodes <- getNodeSet(doc, "//input-id")[[1]]
    removeChildren(ns, .all=TRUE)
    
    # as sub-elements
    kids <- lapply( preKId_2015, function(x) newXMLNode("id", x ))
    addChildren(ns, kids = kids, append = FALSE)
    
    # or insert it as text node:
    addChildren(ns, newXMLTextNode(paste(preKId_2015, collapse = "\n")))