XML - анализ выборочных узлов в R (xml2)

У меня есть входной 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

Вот что мне нужно сделать дальше:

  • Перейдите к тегу bs: stmt внутри out_txns
  • Найдите теги bs: Ntry, bs: Amt и извлеките значение

Я пробовал несколько вещей (xml_find_parents), но не смог найти правильный способ сделать это


person grammar    schedule 31.10.2016    source источник


Ответы (1)


Ваш подход был правильным, но вы слишком быстро пытались сделать многое.

Первый шаг - найти все узлы, а затем сохранить их как вектор узлов, переменную in_out. Затем проанализируйте и отфильтруйте запрошенное «Outward» подмножество из вектора «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"))
person Dave2e    schedule 31.10.2016