2

我有一个 XML 输入文件。该文件包含有关某些交易的数据。XML 文件如下所示:

<?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)为“Outward”的交易金额。

这是我到目前为止所做的:

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

这是我接下来需要做的:

  • 向上导航到 out_txns 中的 bs:stmt 标记
  • 找到 bs:Ntry, bs:Amt 标签并提取值

我已经尝试了一些东西(xml_find_parents)但无法找出正确的方法

4

1 回答 1

2

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

第一步是找到所有节点,然后将它们保存为节点向量,即in_out变量。然后从节点的“in_out”向量中解析和过滤“向外”请求的子集以创建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"))
于 2016-10-31T15:00:24.017 回答