1 2 Previous Next 15 Replies Latest reply: May 17, 2010 7:35 PM by 807580 RSS

    xml to array

    807580
      Hi guys. I am trying to download an XML file, parse it, and return an array (note that I am developing for android, so I do not use print). The following code returns "Error e". Any ideas?
      package com.foo.bar;
      
      import java.io.*;
      import java.net.*;
      import javax.xml.parsers.*;
      import org.xml.sax.*;
      import org.xml.sax.helpers.DefaultHandler;
      import android.app.Activity;
      import android.os.Bundle;
      import android.widget.TextView;
      import javax.xml.parsers.FactoryConfigurationError;
      
      public class foo extends Activity {
          /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
      
              try {
                  SaxP saxp = new SaxP();
                  
                  TextView tv = new TextView(this);
                  
                  tv.setText(saxp.ParseXML());
                  setContentView(tv);
              } catch (Exception e) {
              }
      
      }
      
      
      
          public static class SaxP extends DefaultHandler {
      
              StringBuffer sb;
      
              public SaxP() {
                  sb = new StringBuffer();
              }
      
              @Override
              public void startDocument() throws SAXException {
                  sb.append("<!--l version=\"1.0\"-->\n");
              }
          //
      
              @Override
              public void startElement(String namespaceURI,
                      String localName,
                      String qName,
                      Attributes atts)
                      throws SAXException {
      
                  sb.append("<" + qName);
                  if (atts != null) {
                      for (int i = 0, len = atts.getLength(); i < len; i++) {
                          sb.append(" " + atts.getQName(i)
                                  + "=\"" + atts.getValue(i) + "\"");
                      }
                  }
                  sb.append(">");
              }
      
              @Override
              public void endElement(String namespaceURI,
                      String localName,
                      String qName) throws SAXException {
                  sb.append("\n");
              }
      
              @Override
              public void characters(char[] ch, int start, int len) throws SAXException {
                  sb.append(new String(ch, start, len));
              }
      
              public String ParseXML() {
                  try {
                      URL u;
                      InputStream is = null;
                      DataInputStream dis;
                      String s;
      
                      try {
                          u = new URL("http://www.xe.com/dfs/sample-usd.xml");
                          is = u.openStream();         // throws an IOException
                          // Get SAX Parser Factory
                          SAXParserFactory factory = SAXParserFactory.newInstance();
      
                             // Turn on validation, and turn off namespaces
                             factory.setValidating(true);
                             factory.setNamespaceAware(false);
                             SAXParser sp = factory.newSAXParser();
                             XMLReader parser = sp.getXMLReader();
                             parser.setContentHandler(this);
                             InputSource input = new InputSource(is);
                             parser.parse(input);
                             try {
                                 is.close();
                              }
                             finally
                             {
                                  
                             }
                             return sb.toString();
      
                         } catch (FactoryConfigurationError e) {
                              return "Error occurred obtaining SAX Parser Factory.";
                         } catch (Exception e) {
                              return "Error e";
                         }
      
      
                       } finally {
                       }
                  
      
              }
      
          }
      }
        • 1. Re: xml to array
          793415
          Welcome to the Sun forums.
          josheee12 wrote:
          ..I am trying to download an XML file, parse it, and return an array (note that I am developing for android, so I do not use print). The following code returns "Error e". Any ideas?
          (One idea is) Don't try to code with one arm tied behind your back. More specifically, this..
          ..
          } catch (Exception e) {
               return "Error e";
          }
          ..should be..
           
                            } catch (Exception e) {
                                  e.printStackTrace();
                                  return "Error e";
                            }
          Follow that same basic principle in all the catch statements. Or to put in another way, don't [swallow exceptions|http://pscode.org/javafaq.html#stacktrace].
          • 2. Re: xml to array
            807580
            I can't use "e.printStackTrace" since the data returned is never shown. "return e.getStackTrace().toString" returns [Ljava.lang.StackTraceElement; @44c0148".  Ideas?                                                                                                                                                                                                                                                                                                                                           
            • 3. Re: xml to array
              793415
              josheee12 wrote:
              I can't use "e.printStackTrace" since the data returned is never shown. "return e.getStackTrace().toString" returns [Ljava.lang.StackTraceElement; @44c0148".  Ideas? Where in my reply did I suggest this?{codereturn e.getStackTrace().toString(Which, BTW, would not compile, let alone run.)
              As opposed to
              e.printStackTrace();
              return //whatever...
              Please pay close attention to answers provided.
              • 4. Re: xml to array
                807580
                I can't use e.printStackTrace, since this script is run under Android, which has no CLI output.
                • 5. Re: xml to array
                  807580
                  josheee12 wrote:
                  I can't use e.printStackTrace, since this script is run under Android, which has no CLI output.
                  Can you do logging with Android? Thanks in advance.
                  • 6. Re: xml to array
                    807580
                    Not in any way that I have found. That is why I use:
                    TextView tv = new TextView(this);
                    tv.setText(saxp.ParseXML());
                    setContentView(tv);
                    It generates a new element on the screen (textview), and fills it with the return value (e.getStackTrace). That is because Android is GUI only. There is probably some way to get CLI output from the Terminal Emulator, but I haven't found it.
                    • 7. Re: xml to array
                      807580
                      Google gave me this: [http://www.mathcs.org/java/android/debug.html]

                      Though I'm not sure if this applies to what you are doing.
                      • 8. Re: xml to array
                        807580
                        Ok, I don't know how I missed that. Log here: [http://pastebin.com/EJAUZ4hm|http://pastebin.com/EJAUZ4hm]
                        • 9. Re: xml to array
                          793415
                          josheee12 wrote:
                          Ok, I don't know how I missed that. ..
                          I could not imagine trying to develop without the benefit of the stack trace. It is pure gold.
                          ..Log here: [http://pastebin.com/EJAUZ4hm|http://pastebin.com/EJAUZ4hm]
                          It is better to paste the stack trace directly to the forum. When you do that, make sure you use the code to tags to protect the indentation and formatting of the sample. To use the code tags, select the sample and click the CODE button.
                          ---------------
                          As an aside.
                          a) Even besides the debugging tool/strategy linked earlier (which I did not look at closely), getStackTrace() returns an array, which then normally returns a reference for the array, as the toString(). That reference is what you were seeing. Arrays.toString(Object[]) would transform it into something much more logical.
                          b) Exceptions and Errors in Java are quite distinct, so the method was always inaccurate in reporting that an Error had occured.
                          c) Several things that have occured throughout this thread suggest to me that you are new to Java. Being new to Java, as well as attempting to program in areas where it is more difficult to get at the failure information (e.g. servlets, JSP, applets, JME or other mobile phone programming) is a recipe for disaster.
                          • 10. Re: xml to array
                            807580
                            First of all, the log was too long and gave an error. Secondly, yes, I am new to Java, although I have programmed in several other languages. I guess I could compile my code as CLI then later rewrite as Android.
                            • 11. Re: xml to array
                              793415
                              josheee12 wrote:
                              First of all, the log was too long and gave an error. ..
                              Usually the advice is to post the entire stack trace with no alterations (as you seem to have figured), but those traces for parsing XML can become very long. In that case, I recommend trimming the 'middle half' of the trace. That way, it should show the immediate problem, as well as the underlying cause.
                              ..I guess I could compile my code as CLI then later rewrite as Android.
                              That is a good strategy, but does not solve the immediate problem. After all, if the code is throwing an exception under Android, it should (theoretically) throw the same/similar exception under standard Java.
                              • 12. Re: xml to array
                                807580
                                At least that way, I can use commands such as e.printStackTrace and get the returned value.
                                • 13. Re: xml to array
                                  793415
                                  josheee12 wrote:
                                  At least that way, I can use commands such as e.printStackTrace and get the returned value.
                                  Right. I'd forgotten that (mind like a sieve).
                                  • 14. Re: xml to array
                                    807580
                                    I finally got some code working that reads a file as xml, and turns it into a one-level array. How would I go about putting an element on each level? In php, I could return "hello" using elements[foo][bar][0] with some simple code using this XML:
                                    <foo>
                                    <bar>hello</bar>
                                    </foo>
                                    Is there such a function in Java?
                                    1 2 Previous Next