How to parse a malformed xml (ofx) with ofx4j?

2019-01-24 22:57发布

i am desperatly trying to use the following library : ofx4j. But the documentation relative to parsing an ofx file is a bit lite. It says : If you've got a file or other stream resource, you can read it using an instance of net.sf.ofx4j.io.OFXReader

Ok but how do i do ?

It also states the following: if you want to unmarshal the OFX directly to a Java object, use the net.sf.ofx4j.io.AggregateUnmarshaller.

Fine, but that's a bit complicated for me. Is there something obvious that i missed ? When i try to use the unmarshaller, it asks me to implement an interface.

Could someone point me to an online resource explaining the bits that i am missing ? Or the best, what do you understand from the previous statements relative to the ofxreader and the unmarshaller ?

Please, don't bash me, I am learning java with the playframework and i would really appreciate to be able to parse those ofx files.

thanks in advance.

标签: java xml ofx
2条回答
Evening l夕情丶
2楼-- · 2019-01-24 23:52

I don't see a plain old tutorial, but there's sample code in the test directory that illustrates OFXReader and AggregateUnmarshaller.

The phrase "an instance of net.sf.ofx4j.io.OFXReader" means one of the known implementing classes", such as NanoXMLOFXReader, which is tested here. A test for AggregateUnmarshaller is here.

The API and mail archives are good resources, too. It looks like a lot of institutions participate.

查看更多
不美不萌又怎样
3楼-- · 2019-01-25 00:00

For those that stumble on this like I did when I couldn't get the expected results from the AggregateUnmarshaller... Here is an example.

//Using a multipart file, but using a regular file is similar.
public void parse(MultipartFile file) throws IOException {
  //Use ResponseEnvelope to start.
  AggregateUnmarshaller<ResponseEnvelope> unmarshaller = new AggregateUnmarshaller<ResponseEnvelope>(
    ResponseEnvelope.class);

  try {
    ResponseEnvelope envelope = unmarshaller.unmarshal(file.getInputStream());
    //Assume we are just interested in the credit card info.  Make sure to cast.
    CreditCardResponseMessageSet messageSet = (CreditCardResponseMessageSet) envelope
      .getMessageSet(MessageSetType.creditcard);

    List<CreditCardStatementResponseTransaction> responses = messageSet.getStatementResponses();
    for (CreditCardStatementResponseTransaction response : responses) {
      CreditCardStatementResponse message = response.getMessage();
      String currencyCode = message.getCurrencyCode();
      List<Transaction> transactions = message.getTransactionList().getTransactions();
      for (Transaction transaction : transactions) {
        System.out.println(transaction.getName() + " " + transaction.getAmount() + " "
          + currencyCode);
      }
    }
  }
  catch (OFXParseException e) {
    e.printStackTrace();
  }
}
查看更多
登录 后发表回答