[英]nested XML to data frame in R
您好,我是R和XML文件的新手。
我正在嘗試將此XML SOAP響應放入數據框:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<PrepareDataByClientResponse xmlns="urn:HM-schema">
<PrepareDataByClientResult>
<READOUT>
<SerialNumber>1728527</SerialNumber>
<Date>1510505992000</Date>
<Type>1</Type>
<Value>78.2</Value>
<Status>OK</Status>
</READOUT>
<READOUT>
<SerialNumber>1728527</SerialNumber>
<Date>1510509592000</Date>
<Type>1</Type>
<Value>76.87</Value>
<Status>OK</Status>
</READOUT>
<READOUT>
<SerialNumber>1728527</SerialNumber>
<Date>1510513192000</Date>
<Type>1</Type>
<Value>75.61</Value>
<Status>OK</Status>
</READOUT>
<READOUT>
<SerialNumber>e2ddeed13b4cc4d132f8c6a67d67eed3</SerialNumber>
<Date>4531528776000</Date>
<Type>3</Type>
<Value>230.68</Value>
<Status>OK</Status>
</READOUT>
</PrepareDataByClientResult>
</PrepareDataByClientResponse>
</soap:Body>
</soap:Envelope>
我嘗試了幾種選擇,例如:
xmlout <- do.call(rbind, xpathApply(xmldoc,'//soap:Envelope/soap:Body/PrepareDataByClientResponse', xmlToDataFrame))
xmlout <- as.data.frame(t(xpathSApply(xmldoc,"//readout",function(x) xmlSApply(x,xmlValue))))
xmlout <- as.data.frame(t(xmlSApply(xmldoc["/PrepareDataByClientResponse/PrepareDataByClientResult/READOUT"],xmlAttrs)),stringsAsFactors=FALSE)
xmlout <- ldply(xmlToList(xmldoc), data.frame)
經過對SO和其他Google搜索的廣泛研究,我一直無法產生理想的結果。 我所能得到的是一個只有一行的數據幀,所有觀察值都在不同的列中。
我正在嘗試獲取READOUTS表,例如:
SerialNumber Date Type Value Status
1 1728527 1510505992000 1 78.2 OK
2 1728527 1510509592000 1 76.87 OK
3 1728527 1510513192000 1 75.61 OK
有什么辦法可以使這種表起作用?
提前致謝。
因為您在<PrepareDataByClientResponse>
標記處具有默認名稱空間(即,不帶冒號分隔前綴的xmlns
),所以其所有子級都遵循該默認名稱空間。
要解析<READOUT>
標簽,請考慮聲明要在getNodeSet()
調用中使用的前綴。 下面使用nm 。 然后可以在方便的方法xmlToDataFrame
使用這樣的調用,該方法可以輕松地將相對扁平的XML像您一樣遷移到數據幀中:
library(XML)
doc <- xmlParse('/path/to/SOAP/Response.xml')
df <- xmlToDataFrame(doc, nodes=getNodeSet(doc, "//nm:READOUT",
namespaces=c(nm="urn:HM-schema")))
df
# SerialNumber Date Type Value Status
# 1 1728527 1510505992000 1 78.2 OK
# 2 1728527 1510509592000 1 76.87 OK
# 3 1728527 1510513192000 1 75.61 OK
# 4 e2ddeed13b4cc4d132f8c6a67d67eed3 4531528776000 3 230.68 OK
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.