Java:使用SAX解析xml文件

时间:2014-07-29 15:01:24

标签: java xml parsing soap sax

我使用SAX解析this xml data。问题是我无法弄清楚如何从中获取数据。从中获取最重要的是编码数据(fileContent),我认为它是base64。我需要做的是从它制作一个Excel .xls文件。我尝试了一些东西,但我只能获得一些字段/节点(例如refNumber,userEmail等)名称,但不能获得它们的实际值。我在下面放了一些代码片段。有人可以帮帮我吗?

谢谢!

class SomeClass {
...
private String currentElement;
...
public Result parseSerializedData(String serializedData) throws SAXException, TransformerConfigurationException, TransformerException
    {
        System.out.println("-------------------");
        System.out.println("Serialized: " + serializedData);
        Source src = new SAXSource(xr, new InputSource(new StringReader(serializedData)));
        Result res = new StreamResult(System.out);
        System.out.println("Res 1:" + res);

        TransformerFactory.newInstance().newTransformer().transform(src, res);
        System.out.println("transform 1:" + res);

        try {
         SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser saxParser = factory.newSAXParser();
         saxParser.parse(serializedData, new MyHandler());
          } catch (Exception e) {
             e.printStackTrace();
          }

        System.out.println("The current element is: " + currentElement);
        System.out.println("-------------------");
        return res;
    }

    /*
    * Inner class for the Callback Handlers.
    */
   class MyHandler extends DefaultHandler {
      // Callback to handle element start tag
      @Override
      public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
          System.out.println("qName: " + qName);
         currentElement = qName;
      }

      // Callback to handle element end tag
      @Override
      public void endElement(String uri, String localName, String qName)
            throws SAXException {
         currentElement = "";
      }

      // Callback to handle the character text data inside an element
      @Override
      public void characters(char[] chars, int start, int length) throws SAXException {
        BASE64Decoder decoder = new BASE64Decoder();
          try {
            byte[] decodedBytes = decoder.decodeBuffer(String.valueOf(chars));
              System.out.println("The current element2 is: " + currentElement);
              if (currentElement.equals("fileContent")) {
                System.out.println("\tfileContent:\t" + new String(decodedBytes, start, length));
             }
          } catch (IOException e) {
              e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
          }

      }
   }
}

serializedData是该xml文件的内容

1 个答案:

答案 0 :(得分:0)

基本上characters方法是读取值的地方。在您的情况下,您只打印一个标签。 if (currentElement.equals("fileContent"))。请遵循以下计划。这将显示所有标记的所有值。需要注意的另一件事是characters方法读取最多2048字节的chuck(如果我没记错的话),所以最好的方法是使用append稍后处理endElement()方法中的值,如示例所示。请不要使用DatatypeConverter进行Base64解码。你可以使用自己的解码器。

import java.io.File;

import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxSample {

    public static void main(String argv[]) {

        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {

                StringBuilder value;

                public void startElement(String uri, String localName,
                        String qName, Attributes attributes)
                        throws SAXException {
                    value = new StringBuilder();
                }

                public void endElement(String uri, String localName,
                        String qName) throws SAXException {
                    if ("fileContent".equalsIgnoreCase(qName)) {
                        String decodedValue = new String(DatatypeConverter.parseBase64Binary(value.toString()));
                        System.out.println(qName + " = " + decodedValue);
                    } else {
                        System.out.println(qName + " = " + value);
                    }
                    value = new StringBuilder();
                }

                public void characters(char ch[], int start, int length)
                        throws SAXException {
                    value.append(new String(ch, start, length));
                }

            };

            saxParser.parse(new File("data.xml"), handler);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}