[英]Parsing XML to data.frame in R
對此有很多疑問,但找不到適合這種數據格式的解決方案。 感謝有關如何解析此問題的建議:
<XML>
<constituency hansard_id="5" id="uk.org.publicwhip/cons/1" fromdate="1918" todate="9999-12-31">
<name text="Aberavon"/>
</constituency>
<constituency hansard_id="6" id="uk.org.publicwhip/cons/2" fromdate="1997-05-01" todate="2005-05-04">
<name text="Aberdeen Central"/>
</constituency>
<constituency hansard_id="7" id="uk.org.publicwhip/cons/3" fromdate="1885" todate="9999-12-31">
<name text="Aberdeen North"/>
</constituency>
</XML>
所需的字段顯然是c('hansard_id','id','fromdate','todate','name')
。 讀入和解析我嘗試了以下內容:
require(XML)
> indata = htmlParse('data.xml', isHTML=F)
> class(indata)
[1] "XMLInternalDocument" "XMLAbstractDocument"
> print(indata)
<?xml version="1.0"?>
<XML>
<constituency hansard_id="5" id="uk.org.publicwhip/cons/1" fromdate="1918" todate="9999-12-31">
<name text="Aberavon"/>
</constituency>
<constituency hansard_id="6" id="uk.org.publicwhip/cons/2" fromdate="1997-05-01" todate="2005-05-04">
<name text="Aberdeen Central"/>
</constituency>
<constituency hansard_id="7" id="uk.org.publicwhip/cons/3" fromdate="1885" todate="9999-12-31">
<name text="Aberdeen North"/>
</constituency>
</XML>
> xmlToDataFrame(indata, stringsAsFactors=F)
name
1
2
3
它正在讀取,但xmlToDataFrame
無法處理格式。 是因為數據是'constituency'標簽元素的屬性嗎? 非常感謝任何指導。
你是對的, xmlToDataFrame
只訪問XML
節點。 對於給定節點, xmlAttrs
函數將返回該節點屬性。 xpathApply
函數接受解析的xml文檔doc
say並將xpath
應用於它以獲取一組節點。 然后將這些節點中的每一個應用於用戶定義的功能。 xpath
"//*/constituency"
將返回文檔中的所有constituency
節點。 然后我們可以將xmlAttrs
函數應用於每個:
res <- xpathApply(doc, "//*/constituency", xmlAttrs)
這將返回一個屬性列表。 我們想將這些綁定在一起,例如:
rbind.data.frame(res[[1]], res[[2]], ...)
將第一個和第二個,第三個,......組的屬性綁定到data.frame中。 這樣做的一個簡單方法是在out屬性列表中使用do.call
函數:
do.call(rbind.data.frame, res)
將行綁定應用於列表的所有元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.