2016-03-03 120 views
3

我想從使用R的XML庫的網站中提取一些信息。將XMLNodeSet轉換爲格式良好的XML文檔

我已經下載了一個網頁。然後,我使用Xpath表達式從頁面中提取一些相關元素。通常這導致約50個這些相關元素。然後我想將這些相關項目(XMLNodeSet)保存爲XML文檔(這樣我就可以在XML編輯器中分析結果)。

但是。之前,我可以保存XMLNodeSet,我需要在使用XML :: saveXML()函數之前將它們轉換爲格式良好的xml文檔。

有沒有人有任何想法如何使用R的XML包做到這一點。以下是代碼片段:

download.file("https://www.holidayhouses.co.nz/Browse/List.aspx?page=37", "data.html") 
doc <- htmlParse("data.html") 
# set up x-path 
str_x_path_lccg <- "//div[@class = 'ListCard-content group']" 
# extract relevant nodes 
xml_relevant_nodes <- XML::getNodeSet(doc, str_x_path_lccg) 
# need to convert xml_relevant_nodes into a well-formed xml document in order to save it 
# therefore the following fails 
XML::saveXML(xml_relevant_nodes, "test.xml") 

任何想法......?

回答

2

既然問了這個問題,我已經多瞭解了R的XML包。下面是最初問到的問題的答案:

download.file("https://www.holidayhouses.co.nz/Browse/List.aspx?page=37", "data.html") 
doc <- htmlParse("data.html") 
# set up x-path 
str_x_path_lccg <- "//div[@class = 'ListCard-content group']" 
# extract relevant nodes 
xml_relevant_nodes <- XML::getNodeSet(doc, str_x_path_lccg) 
# need to convert xml_relevant_nodes into a well-formed xml document in order to save it 
# firstly, create a single node which will be the parent 
xmlDoc = newXMLNode("top", "topNode", namespace = c(tfm = "http://www.thefactmachine.com")) 
# now we can add the node set to the parent node 
addChildren(xmlDoc, kids = xml_relevant_nodes) 
XML::saveXML(xmlDoc, "test.xml")