2016-03-23 6 views
1

Мне нужно распечатать заказ на каждого клиента в этом примере XML-файла.XML SAX Parsing

<OrderID id="10248"> 
<CustomerID>VINET</CustomerID> 
<ProductName>Queso Cabrales</ProductName> 
<UnitPrice>14.0000</UnitPrice> 
<Quantity>12</Quantity> 
<Freight>32.3800</Freight> 
</OrderID> 
<OrderID id="10248"> 
<CustomerID>VINET</CustomerID> 
<ProductName>Singaporean Hokkien Fried Mee</ProductName> 
<UnitPrice>9.8000</UnitPrice> 
<Quantity>10</Quantity> 
<Freight>32.3800</Freight> 
</OrderID> 
<OrderID id="10248"> 
<CustomerID>VINET</CustomerID> 
<ProductName>Mozzarella di Giovanni</ProductName> 
<UnitPrice>34.8000</UnitPrice> 
<Quantity>5</Quantity> 
<Freight>32.3800</Freight> 
</OrderID> 
<OrderID id="10249"> 
<CustomerID>TOMSP</CustomerID> 
<ProductName>Tofu</ProductName> 
<UnitPrice>18.6000</UnitPrice> 
<Quantity>9</Quantity> 
<Freight>11.6100</Freight> 
</OrderID> 
<OrderID id="10249"> 
<CustomerID>TOMSP</CustomerID> 
<ProductName>Manjimup Dried Apples</ProductName> 
<UnitPrice>42.4000</UnitPrice> 
<Quantity>40</Quantity> 
<Freight>11.6100</Freight> 
</OrderID> 

Что я хотел бы это результат выглядеть так:

VINET: 537,14

TOMSP: 1886,62

и т.д.

Эти итоговые сделаны из UnitPrice * Количество + Фрахт, предложенный по результатам. Если бы я дал вам остальную часть XML, вы могли бы видеть ее лучше, но ради времени я уменьшил ее. Я также получаю ошибку, делая десятичный формат для этих трех переменных, и я не уверен, почему.

public class DataProcessor2 extends DefaultHandler { 

    boolean unitPrice = false; 
    boolean collectCount = false; 
    boolean freight = false;; 
    boolean quantity = false; 
    boolean customer = false; 

    float currentCount = 0; 
    float totalCount = 0; 
    float unitPriceCount = 0; 
    float freightCount = 0; 
    float quantityCount = 0; 

    //unitprice, freight, quantity 

    public DataProcessor2(){ 
     super(); 
    } 

    public void startDocument() { 
     // TODO Auto-generated method stub 
     System.out.println("Order Totals Per Customer"); 
    } 

    public void endDocument() { 
     // TODO Auto-generated method stub 

     System.out.println("Document END"); 
    } 

    public void startElement(String namespaceUri, String localName, 
      String qualifiedName, Attributes attributes) { 

     DecimalFormat df = new DecimalFormat("0.00"); 
     df.setMaximumFractionDigits(2); 
     if (qualifiedName.equals("CustomerID")){ 
      customer = true; 
     } 
     if(qualifiedName.equals("UnitPrice")){ 
      unitPrice = true; 
      //unitPriceCount = Float.parseFloat((qualifiedName)); 
     } 
     if(qualifiedName.equalsIgnoreCase("Freight")){ 
      freight = true; 
      //freightCount = Float.parseFloat(df.format(qualifiedName)); 
     } 
     if(qualifiedName.equalsIgnoreCase("Quantity")){ 
      quantity = true; 
      //quantityCount = Float.parseFloat(df.format(qualifiedName)); 
     } 
     if(unitPrice & freight & quantity){ 
      collectCount = true; 
      //currentCount = unitPriceCount * quantityCount + freightCount; 
     } 

    } 
    public void endElement(String namespaceUri, String localName, 
      String qualifiedName, Attributes attributes) { 
     //System.out.println("End Element "+ qualifiedName); 
    } 
    public void characters (char[] ch, int start, int length) throws SAXException{ 

     if (customer) { 
      System.out.println(new String(ch, start, length)); 
      customer = false; 
      } 
     if(unitPrice){ 
      // System.out.println(new String(ch, start, length)); 
      unitPrice = false; 
     } 
     if(freight){ 
      //System.out.println(new String(ch, start, length)); 
      freight = false; 
     } 
     if(quantity){ 
      //System.out.println(new String(ch, start, length)); 
      quantity = false; 
     } 
     if(collectCount){ 
      //System.out.println("Amount"+new String(ch, start, length)); 
      collectCount = false; 
     } 
     if(unitPrice & freight & quantity){ 
       collectCount = true; 
       //currentCount = unitPriceCount * quantityCount + freightCount; 
      } 

    } 

} 

ОШИБКА:

Exception in thread "main" java.lang.NumberFormatException: For input string: "UnitPrice" 
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) 
    at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122) 
    at java.lang.Float.parseFloat(Float.java:451) 
    at DataProcessor2.startElement(DataProcessor2.java:50) 
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509) 
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:379) 
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2786) 
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606) 
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117) 
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) 
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848) 
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777) 
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) 
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213) 
    at One.main(One.java:19) 
+1

предоставить код и ошибки – JEY

+0

Отредактированный код и ошибки заданной – th30d0rab1e

+5

Вы пытаетесь разбора ** String ** '" UnitPrice "' как float 'unitPriceCount = Float.parseFloat ((qualName));'. Вы должны проанализировать значение, а не имя. – Berger

ответ

0

Ниже приведен код, чтобы сделать это в VTD-XML

import com.ximpleware.*; 

public class xpathSearch { 
    private static double compute(VTDNav vn) throws VTDException{ 
     double d1=0,d2=0; 
     if (vn.toElement(VTDNav.NEXT_SIBLING,"UnitPrice")){ 
      int i=vn.getText(); 
      if (i!=-1) 
      d1 = vn.parseDouble(i); 
     } 
     if (vn.toElement(VTDNav.NEXT_SIBLING,"Quantity")){ 
      int i=vn.getText(); 
      if (i!=-1) 
      d2 = vn.parseDouble(i); 
     } 
     return d1*d2; 
    } 
    public static void main(String s[])throws VTDException{ 
     VTDGen vg = new VTDGen(); 
     if (!vg.parseFile("d:\\xml\\input2.txt", false)) 
       return; 
     VTDNav vn = vg.getNav(); 
     AutoPilot ap = new AutoPilot(vn); 
     ap.selectXPath("/root/OrderID"); 
     int i; 
     double p1=0,p2 = 0; 
     while ((i=ap.evalXPath())!=-1){ 
      if (vn.toElement(VTDNav.FIRST_CHILD,"CustomerID")){ 
       i = vn.getText(); 
       if (i!=-1) { 
        if(vn.matchTokenString(i, "TOMSP")){ 
         p1 += compute(vn); 
        } 
        else if (vn.matchTokenString(i, "VINET")){ 

         p2 += compute(vn); 
        } 
       } 
       vn.toElement(VTDNav.P); 
      } 
     } 

     System.out.println(" TOMSP "+p1); 
     System.out.println(" VINET "+p2); 

    } 
} 
Смежные вопросы