2016-10-31 34 views
2

我有一个XML输入文件。该文件有一些交易的数据。 XML文件是这样的:XML - 解析R(xml2)中的选择性节点

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Message xmlns:bs="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02" 
     xmlns="urn:bcsis" 
     xmlns:head="urn:iso:std:iso:20022:tech:xsd:head.001.001.01"> 
<bs:stmt> 
    <bs:Bal> 
    <bs:Tp> 
     <bs:CdOrPrtry> 
     <bs:Prtry>Outward</bs:Prtry> 
     </bs:CdOrPrtry> 
    </bs:Tp> 
    <bs:Amt Ccy="USD">300.00</bs:Amt> 
    <bs:CdtDbtInd>DBIT</bs:CdtDbtInd> 
    <bs:Dt> 
     <bs:Dt>2016-10-04</bs:Dt> 
    </bs:Dt> 
    </bs:Bal> 
    <bs:Ntry> 
    <bs:Amt Ccy="USD">300.00</bs:Amt> 
    </bs:Ntry> 
</bs:stmt> 
<bs:stmt> 
    <bs:Bal> 
    <bs:Tp> 
     <bs:CdOrPrtry> 
     <bs:Prtry>Inward</bs:Prtry> 
     </bs:CdOrPrtry> 
    </bs:Tp> 
    <bs:Amt Ccy="USD">250.00</bs:Amt> 
    <bs:CdtDbtInd>DBIT</bs:CdtDbtInd> 
    <bs:Dt> 
     <bs:Dt>2016-10-04</bs:Dt> 
    </bs:Dt> 
    </bs:Bal> 
    <bs:Ntry> 
    <bs:Amt Ccy="USD">250.00</bs:Amt> 
    </bs:Ntry> 
</bs:stmt> 
</Message> 

我需要提取交易金额在交易类型(BS:Prtry)是“外化”。

这是我迄今所做的:

library(xml2) 
library(XML) 
library(dplyr) 

d <- read_xml("~/CEED/sample1.dat") # read the file 
in_out <- xml_find_all(d, ".//bs:stmt/bs:Bal/bs:Tp/bs:CdOrPrtry/bs:Prtry") # Transaction Type 
out_txns <- in_out[which(in_out %>% xml_text() == "Outward")] # Select only Outward 

这是我下一步需要做:

  • 导航到BS:out_txns内语句标签
  • 找到bs:Ntry,bs:Amt标记并提取值

我尝试过几件事(xml_find_parents),但没有能够找出正确的方法做到这一点

回答

2

你的方法是在正确的轨道上,但你试图做得太早。

第一步是找到所有的节点,然后将它们保存为节点的向量,变量为in_out。然后从节点的“in_out”向量中解析和过滤“Outward”请求的子集,以创建out_txns。从这个缩小的节点列表中提取请求的“数量”信息。

library(xml2) 
d<-read_xml("~/CEED/sample1.dat") # read the file 

#find all of the stmt nodes 
in_out <- xml_find_all(d, ".//bs:stmt") # Transaction Type 

#filter the nodes and Select only Outward 
out_txns <- in_out[xml_text(xml_find_first(in_out, ".//bs:Prtry")) == "Outward"] 
#Extract the amounts from the remianing nodes 
amount<-xml_text(xml_find_first(out_txns, ".//bs:Amt"))