01: /* Copyright 2004 The Apache Software Foundation
02: *
03: * Licensed under the Apache License, Version 2.0 (the "License");
04: * you may not use this file except in compliance with the License.
05: * You may obtain a copy of the License at
06: *
07: * http://www.apache.org/licenses/LICENSE-2.0
08: *
09: * Unless required by applicable law or agreed to in writing, software
10: * distributed under the License is distributed on an "AS IS" BASIS,
11: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: * See the License for the specific language governing permissions and
13: * limitations under the License.
14: */
15: package org.apache.xmlbeans.samples.cursor;
16:
17: import statement.StatementDocument;
18: import statement.StatementDocument.Statement;
19: import statement.Transaction;
20: import java.io.File;
21:
22: import org.apache.xmlbeans.XmlCursor;
23:
24: import javax.xml.namespace.QName;
25:
26: public class OrderMatters {
27: private static QName deposit = new QName("http://statement",
28: "deposit");
29:
30: public static void main(String[] args) throws Exception {
31: // load the xml instance into the store and return a
32: // strongly typed instance of StatementDocument
33: StatementDocument stmtDoc = StatementDocument.Factory
34: .parse(new File(args[0]));
35:
36: System.out.println("Valid statement instance? "
37: + stmtDoc.validate());
38:
39: float balance = balanceOutOfOrder(stmtDoc);
40:
41: System.out.println("Ending balance: $" + balance);
42:
43: balance = balanceInOrder(stmtDoc);
44:
45: System.out.println("Ending balance: $" + balance);
46: }
47:
48: /**
49: * Out of order balance: the ease of stronly-typed XmlObjects!
50: */
51: public static float balanceOutOfOrder(StatementDocument stmtDoc) {
52: Statement stmt = stmtDoc.getStatement();
53:
54: float balance = 0;
55:
56: Transaction[] deposits = stmt.getDepositArray();
57: Transaction[] withdrawals = stmt.getWithdrawalArray();
58:
59: for (int i = 0; i < deposits.length; i++)
60: balance += deposits[i].getAmount();
61:
62: for (int i = 0; i < withdrawals.length; i++)
63: balance -= withdrawals[i].getAmount();
64:
65: return balance;
66: }
67:
68: /**
69: * In order balance: the power of XmlCursor!
70: */
71: public static float balanceInOrder(StatementDocument stmtDoc) {
72: float balance = 0;
73:
74: XmlCursor cursor = stmtDoc.newCursor();
75:
76: // use xpath to select elements
77: cursor.selectPath("*/*");
78:
79: // iterate over the selection
80: while (cursor.toNextSelection()) {
81: // two views of the same data:
82: // move back and forth between XmlObject <-> XmlCursor
83: Transaction trans = (Transaction) cursor.getObject();
84:
85: float amount = trans.getAmount();
86:
87: if (cursor.getName().equals(deposit))
88: balance += amount;
89: else if ((balance -= amount) < 0) {
90: // doh!
91: System.out.println("Negative balance: $" + balance);
92: balance -= 50;
93: }
94: }
95:
96: return balance;
97: }
98:
99: }
|