Ejemplo n.º 1
0
 private static Element parseElement(XMLStreamReader xsr) throws XMLStreamException {
   // xsr points to a START_ELEMENT event. Create the element and read all its attributes
   // Then read all its children events
   Element element = new Element(xsr.getLocalName());
   // text that will be added to the element. Text can come in different events, so we add it here
   // and add it to the element at the end
   StringBuilder elementText = new StringBuilder();
   int attributeCount = xsr.getAttributeCount();
   for (int i = 0; i < attributeCount; i++) {
     element.putAttribute(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
   }
   while (xsr.hasNext()) {
     xsr.next();
     if (xsr.getEventType() == XMLStreamConstants.END_ELEMENT) {
       // element is closed. Move the cursor and return it
       // check if there is some text to add before (empty text is not added, but added text is not
       // trimmed)
       // we set empty text also if the element has no children
       if (!elementText.toString().trim().isEmpty() || !element.hasChildren()) {
         element.setText(elementText.toString());
       }
       //                xsr.next();
       return element;
     } else if (xsr.getEventType() == XMLStreamConstants.CHARACTERS) {
       // an attribute of the current element
       elementText.append(xsr.getText());
     } else if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
       // new element begins -> read it recursively and add it to the current element
       element.addChild(parseElement(xsr));
     }
   }
   // we reached the end of the document without the tag end -> error parsing
   throw new XMLStreamException(
       "End of the document unexpectedly reached. Element " + element.getName() + " not closed");
 }
Ejemplo n.º 2
0
 //    public static void write(OutputStream stream, Element element, int hashLength) throws
 // XMLStreamException {
 //        XMLOutputFactory xof = XMLOutputFactory.newInstance();
 //        IndentingXMLStreamWriter xtw = new
 // IndentingXMLStreamWriter(xof.createXMLStreamWriter(stream));
 //        writeXMLStreamWriter(xtw, element, hashLength);
 //    }
 //
 private static void writeXMLStreamWriter(XMLStreamWriter xtw, Element element, int hashLength)
     throws XMLStreamException {
   if (hashLength > 0) {
     String hash = element.getHash(hashLength);
     Element hashElement = new Element(CRC_ELEMENT);
     hashElement.setText(hash);
     element.addChild(hashElement);
   }
   writeElement(xtw, element);
   xtw.writeEndDocument();
   xtw.flush();
   xtw.close();
   if (hashLength > 0) {
     element.removeChildren(CRC_ELEMENT);
   }
 }