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

人走茶凉 提交于 2019-12-29 06:33:24

问题


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.


回答1:


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.




回答2:


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();
  }
}


来源:https://stackoverflow.com/questions/2221608/how-to-parse-a-malformed-xml-ofx-with-ofx4j

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!