Java Code Examples for javax.xml.stream.events.XMLEvent#asStartElement()

The following examples show how to use javax.xml.stream.events.XMLEvent#asStartElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VespaRecordWriter.java    From vespa with Apache License 2.0 6 votes vote down vote up
private String findDocIdFromXml(String xml) {
    try {
        XMLEventReader eventReader = XMLInputFactory.newInstance().createXMLEventReader(new StringReader(xml));
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event.getEventType() == XMLEvent.START_ELEMENT) {
                StartElement element = event.asStartElement();
                String elementName = element.getName().getLocalPart();
                if (VespaDocumentOperation.Operation.valid(elementName)) {
                    return element.getAttributeByName(QName.valueOf("documentid")).getValue();
                }
            }
        }
    } catch (XMLStreamException | FactoryConfigurationError e) {
        // as json dude does
        return null;
    }
    return null;
}
 
Example 2
Source File: CimAnonymizer.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
private void addRdfIdValues(InputStream is, Set<String> rdfIdValues) throws XMLStreamException {
    // memoize RDF ID values of the document
    XMLEventReader eventReader = xmlStaxContext.inputFactory.createXMLEventReader(is);
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isStartElement()) {
            StartElement startElement = event.asStartElement();
            Iterator it = startElement.getAttributes();
            while (it.hasNext()) {
                Attribute attribute = (Attribute) it.next();
                QName name = attribute.getName();
                if (RDF_ID.equals(name)) {
                    rdfIdValues.add(attribute.getValue());
                }
            }
        }
    }
    eventReader.close();
}
 
Example 3
Source File: CheckstyleConfigurationsParser.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Recursively processes parsing of the configuration XML file with StAX parser.
 * Configuration XML has recursive tree structure
 * where module tags are nested into other module tags, also
 * duplicates of the same modules may be present in one configuration,
 * so there are no other option but to parse configuration
 * into the same tree structure.
 *
 * @param reader
 *        StAX parser interface.
 * @param parent
 *        parent module tag.
 * @throws XMLStreamException
 *         on internal StAX parser error.
 */
private static void parseModule(XMLEventReader reader, ConfigurationModule parent)
        throws XMLStreamException {
    while (reader.hasNext()) {
        final XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            final StartElement startElement = event.asStartElement();
            final String startElementName = startElement.getName()
                    .getLocalPart();
            // module tag encounter
            if (startElementName.equals(MODULE_TAG)) {
                processModuleTag(reader, startElement, parent);
            }
            // property tag encounter
            else if (startElementName.equals(PROPERTY_TAG)) {
                processPropertyTag(startElement, parent);
            }
            // message tag encounter
            else if (startElementName.equals(MESSAGE_TAG)) {
                processMessageTag(startElement, parent);
            }
        }
        if (event.isEndElement()) {
            final EndElement endElement = event.asEndElement();
            if (endElement.getName().getLocalPart().equals(MODULE_TAG)) {
                // return from recursive method
                break;
            }
        }
    }
}
 
Example 4
Source File: DefaultAttributeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testEventReader() {
    try {
        XMLInputFactory ifac = XMLInputFactory.newInstance();
        XMLEventReader read = ifac.createXMLEventReader(this.getClass().getResource(INPUT_FILE).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE));
        while (read.hasNext()) {
            XMLEvent event = read.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                if (startElement.getName().getLocalPart().equals("bookurn")) {
                    Iterator iterator = startElement.getNamespaces();
                    int count = 0;
                    while (iterator.hasNext()) {
                        iterator.next();
                        count++;
                    }
                    Assert.assertTrue(count == 2, "Two namespaces are expected for <bookurn> ");

                    Iterator attributes = startElement.getAttributes();
                    count = 0;
                    while (attributes.hasNext()) {
                        iterator.next();
                        count++;
                    }
                    Assert.assertTrue(count == 0, "Zero attributes are expected for <bookurn> ");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example 5
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private String unmarshalNodeContent(final NamespaceVersion nsVersion, final ModelNode node, final QName nodeElementName, final XMLEventReader reader) throws PolicyException {
    StringBuilder valueBuffer = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent xmlParserEvent = reader.nextEvent();
            switch (xmlParserEvent.getEventType()) {
                case XMLStreamConstants.COMMENT:
                    break; // skipping the comments
                case XMLStreamConstants.CHARACTERS:
                    valueBuffer = processCharacters(node.getType(), xmlParserEvent.asCharacters(), valueBuffer);
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    checkEndTagName(nodeElementName, xmlParserEvent.asEndElement());
                    break loop; // data exctraction for currently processed policy node is done
                case XMLStreamConstants.START_ELEMENT:
                    final StartElement childElement = xmlParserEvent.asStartElement();

                    ModelNode childNode = addNewChildNode(nsVersion, node, childElement);
                    String value = unmarshalNodeContent(nsVersion, childNode, childElement.getName(), reader);

                    if (childNode.isDomainSpecific()) {
                        parseAssertionData(nsVersion, value, childNode, childElement);
                    }
                    break;
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0011_UNABLE_TO_UNMARSHALL_POLICY_XML_ELEM_EXPECTED()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }

    return (valueBuffer == null) ? null : valueBuffer.toString().trim();
}
 
Example 6
Source File: ExternalAttachmentsUnmarshaller.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private Map<URI, Policy> unmarshal(final XMLEventReader reader, final StartElement parentElement) throws PolicyException {
    XMLEvent event = null;
    while (reader.hasNext()) {
        try {
            event = reader.peek();
            switch (event.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                case XMLStreamConstants.COMMENT:
                    reader.nextEvent();
                    break;

                case XMLStreamConstants.CHARACTERS:
                    processCharacters(event.asCharacters(), parentElement, map);
                    reader.nextEvent();
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    processEndTag(event.asEndElement(), parentElement);
                    reader.nextEvent();
                    return map;

                case XMLStreamConstants.START_ELEMENT:
                    final StartElement element = event.asStartElement();
                    processStartTag(element, parentElement, reader, map);
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    return map;

                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0087_UNKNOWN_EVENT(event)));
            }
        } catch (XMLStreamException e) {
            final Location location = event == null ? null : event.getLocation();
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(location)), e);
        }
    }
    return map;
}
 
Example 7
Source File: RestXMLResponseParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private MessagePart parseChildMessage(XMLEventReader reader) throws XMLStreamException {
    MessagePart msg = new MessagePart();
    int level = 0;
    while (reader.hasNext() && (level > -1)) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            if (level++ == 0) {
                StartElement element = event.asStartElement();
                String elementName = element.getName().getLocalPart();
                if (ENTRY.equals(elementName)) {
                    Map<String, String> m = getMapEntry(element);
                    String key = m.get("key");
                    String value = m.get("value");
                    switch (key) {
                        case "message":
                            msg.setMessage(value);
                            break;
                        case "properties":
                            msg.props = parseProperties(reader);
                            break;
                        case "children":
                            msg.children = parseChildrenMessages(reader);
                            break;
                    }
                }
            }
        } else {
            level--;
        }
    }
    return msg;
}
 
Example 8
Source File: ArtifactsXmlAbsoluteUrlRemover.java    From nexus-repository-p2 with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isStartTagWithName(@Nullable final XMLEvent tag, final String name) {
  if (tag != null && tag.getEventType() == START_ELEMENT) {
    StartElement startElement = tag.asStartElement();
    if (startElement.getName().getLocalPart().equals(name)) {
      return true;
    }
  }
  return false;
}
 
Example 9
Source File: SearchHandle.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
private void handleFacet(XMLEventReader reader, StartElement element)
  throws XMLStreamException
{
  if (tempFacets == null) {
    tempFacets = new LinkedHashMap<>();
  }

  String facetName = getAttribute(element, "name");

  List<FacetValue> values = new ArrayList<>();

  QName facetValuesName = new QName(SEARCH_NS, "facet-value");

  QName facetElementName = element.getName();
  events: while (reader.hasNext()) {
    XMLEvent event = reader.nextEvent();

    int eventType = event.getEventType();
    switch (eventType) {
      case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        if (facetValuesName.equals(startElement.getName())) {
          values.add(handleFacetValue(reader, startElement));
        } else {
          logger.warn("Unexpected facet element "+startElement.getName().toString());
        }
        break;
      case XMLStreamConstants.END_ELEMENT:
        if (facetElementName.equals(event.asEndElement().getName())) {
          break events;
        }
        break;
    }
  }

  tempFacets.put(
    facetName,
    new FacetResultImpl(facetName,
      values.toArray(new FacetValue[values.size()])));
}
 
Example 10
Source File: StreamingWorkbookReader.java    From components with Apache License 2.0 5 votes vote down vote up
void lookupSheetNames(InputStream workBookData) throws IOException, InvalidFormatException, XMLStreamException {
    sheetNames.clear();

    XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(workBookData);
    boolean parsingsSheets = false;
    while (parser.hasNext()) {
        XMLEvent event = parser.nextEvent();
        switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            StartElement startElement = event.asStartElement();
            String tagLocalName = startElement.getName().getLocalPart();
            if ("sheets".equals(tagLocalName)) {
                parsingsSheets = true;
                continue;
            }
            if (parsingsSheets && "sheet".equals(tagLocalName)) {
                Attribute attribute = startElement.getAttributeByName(SHEET_NAME_ATT_QNAME);
                if (attribute != null) {
                    sheetNames.add(attribute.getValue());
                }
            }

            break;
        case XMLStreamConstants.END_ELEMENT:
            if ("sheets".equals(event.asEndElement().getName().getLocalPart())) {
                return;
            }
        }
    }
}
 
Example 11
Source File: SememeParser.java    From similarity with Apache License 2.0 5 votes vote down vote up
/**
 * 文件加载义原
 */
private void load(InputStream inputStream) throws IOException {
    long time = System.currentTimeMillis();
    int count = 0;
    try {
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(inputStream);

        while (xmlEventReader.hasNext()) {
            XMLEvent event = xmlEventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();
                if (startElement.getName().toString().equals("sememe")) {
                    String cnWord = startElement.getAttributeByName(QName.valueOf("cn")).getValue();
                    String id = startElement.getAttributeByName(QName.valueOf("id")).getValue();
                    SEMEMES.put(cnWord, id);
                    count++;
                }
            }
        }
        inputStream.close();
    } catch (Exception e) {
        logger.error("xml err:" + e.toString());
        e.printStackTrace();
    }
    time = System.currentTimeMillis() - time;
    logger.info("complete! count num:" + count + ". time spend:" + time + "ms");
}
 
Example 12
Source File: XmlPolicyModelUnmarshaller.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private String unmarshalNodeContent(final NamespaceVersion nsVersion, final ModelNode node, final QName nodeElementName, final XMLEventReader reader) throws PolicyException {
    StringBuilder valueBuffer = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent xmlParserEvent = reader.nextEvent();
            switch (xmlParserEvent.getEventType()) {
                case XMLStreamConstants.COMMENT:
                    break; // skipping the comments
                case XMLStreamConstants.CHARACTERS:
                    valueBuffer = processCharacters(node.getType(), xmlParserEvent.asCharacters(), valueBuffer);
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    checkEndTagName(nodeElementName, xmlParserEvent.asEndElement());
                    break loop; // data exctraction for currently processed policy node is done
                case XMLStreamConstants.START_ELEMENT:
                    final StartElement childElement = xmlParserEvent.asStartElement();

                    ModelNode childNode = addNewChildNode(nsVersion, node, childElement);
                    String value = unmarshalNodeContent(nsVersion, childNode, childElement.getName(), reader);

                    if (childNode.isDomainSpecific()) {
                        parseAssertionData(nsVersion, value, childNode, childElement);
                    }
                    break;
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0011_UNABLE_TO_UNMARSHALL_POLICY_XML_ELEM_EXPECTED()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }

    return (valueBuffer == null) ? null : valueBuffer.toString().trim();
}
 
Example 13
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private String unmarshalNodeContent(final NamespaceVersion nsVersion, final ModelNode node, final QName nodeElementName, final XMLEventReader reader) throws PolicyException {
    StringBuilder valueBuffer = null;

    loop:
    while (reader.hasNext()) {
        try {
            final XMLEvent xmlParserEvent = reader.nextEvent();
            switch (xmlParserEvent.getEventType()) {
                case XMLStreamConstants.COMMENT:
                    break; // skipping the comments
                case XMLStreamConstants.CHARACTERS:
                    valueBuffer = processCharacters(node.getType(), xmlParserEvent.asCharacters(), valueBuffer);
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    checkEndTagName(nodeElementName, xmlParserEvent.asEndElement());
                    break loop; // data exctraction for currently processed policy node is done
                case XMLStreamConstants.START_ELEMENT:
                    final StartElement childElement = xmlParserEvent.asStartElement();

                    ModelNode childNode = addNewChildNode(nsVersion, node, childElement);
                    String value = unmarshalNodeContent(nsVersion, childNode, childElement.getName(), reader);

                    if (childNode.isDomainSpecific()) {
                        parseAssertionData(nsVersion, value, childNode, childElement);
                    }
                    break;
                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0011_UNABLE_TO_UNMARSHALL_POLICY_XML_ELEM_EXPECTED()));
            }
        } catch (XMLStreamException e) {
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
        }
    }

    return (valueBuffer == null) ? null : valueBuffer.toString().trim();
}
 
Example 14
Source File: ExternalAttachmentsUnmarshaller.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private Map<URI, Policy> unmarshal(final XMLEventReader reader, final StartElement parentElement) throws PolicyException {
    XMLEvent event = null;
    while (reader.hasNext()) {
        try {
            event = reader.peek();
            switch (event.getEventType()) {
                case XMLStreamConstants.START_DOCUMENT:
                case XMLStreamConstants.COMMENT:
                    reader.nextEvent();
                    break;

                case XMLStreamConstants.CHARACTERS:
                    processCharacters(event.asCharacters(), parentElement, map);
                    reader.nextEvent();
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    processEndTag(event.asEndElement(), parentElement);
                    reader.nextEvent();
                    return map;

                case XMLStreamConstants.START_ELEMENT:
                    final StartElement element = event.asStartElement();
                    processStartTag(element, parentElement, reader, map);
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    return map;

                default:
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0087_UNKNOWN_EVENT(event)));
            }
        } catch (XMLStreamException e) {
            final Location location = event == null ? null : event.getLocation();
            throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(location)), e);
        }
    }
    return map;
}
 
Example 15
Source File: ParseWikipedia.java    From WikipediaEntities with GNU Affero General Public License v3.0 5 votes vote down vote up
private void parsePage(XMLEventReader eventReader) throws XMLStreamException, InterruptedException {
  String title = null, text = null, redirect = null;
  boolean skip = false;
  while(eventReader.hasNext()) {
    XMLEvent event = eventReader.nextEvent();
    if(event.isEndElement() && event.asEndElement().getName().getLocalPart() == "page") {
      break;
    }
    if(!skip && event.isStartElement()) {
      StartElement startElement = event.asStartElement();
      // Ignore non-main pages
      if(startElement.getName().getLocalPart() == "ns")
        skip |= !"0".equals(parseTextContents(eventReader));

      if(startElement.getName().getLocalPart() == "title")
        title = parseTextContents(eventReader);

      if(startElement.getName().getLocalPart() == "text")
        text = parseTextContents(eventReader);

      if(startElement.getName().getLocalPart() == "redirect")
        redirect = startElement.getAttributeByName(TITLEQNAME).getValue();
    }
  }
  // Post-process page.
  if(!skip && redirect == null && text == null && title != null)
    System.err.println("No redirect or text, but title: " + title);
  // Ignore non-main pages
  if(skip || title == null || text == null)
    return;
  queue.put(new Article(prefix, title, redirect, text));
  readprog.incrementAndLog();
}
 
Example 16
Source File: ConfigReader.java    From ballerina-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Process XML as a stream of events
 *
 * @param inputStream
 */
public void readXML(InputStream inputStream) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    try {
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(inputStream);

        while (eventReader.hasNext()) {
            XMLEvent xmlEvent = eventReader.nextEvent();
            switch (xmlEvent.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                StartElement startElement = xmlEvent.asStartElement();
                checkFlowState(getElementOrAttributeName(startElement.getName()), true);
                loadIntermediateMuleObjects(startElement);
                break;

            case XMLStreamConstants.CHARACTERS:
                break;

            case XMLStreamConstants.END_ELEMENT:
                EndElement endElement = xmlEvent.asEndElement();
                checkFlowState(getElementOrAttributeName(endElement.getName()), false);
                break;

            default:
                break;
            }
        }
    } catch (XMLStreamException e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example 17
Source File: SearchHandle.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
private void collectResult(XMLEventReader reader, StartElement element)
  throws XMLStreamException
{
  QName snippetName       = new QName(SEARCH_NS, "snippet");
  QName extractedName     = new QName(SEARCH_NS, "extracted");
  QName extractedNoneName = new QName(SEARCH_NS, "extracted-none");
  QName metadataName      = new QName(SEARCH_NS, "metadata");
  QName similarName       = new QName(SEARCH_NS, "similar");
  QName relevanceInfoName = new QName(QUERY_NS,  "relevance-info");

  List<XMLEvent> eventBuf = new ArrayList<>();

  QName resultName = element.getName();
  events: while (reader.hasNext()) {
    XMLEvent event = reader.nextEvent();

    int eventType = event.getEventType();
    eventType: switch (eventType) {
      case XMLStreamConstants.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        QName startName = startElement.getName();
        if (snippetName.equals(startName)) {
          handleSnippet(reader, startElement);
        } else if (extractedName.equals(startName)) {
          handleExtracted(reader, startElement);
        } else if (extractedNoneName.equals(startName)) {
          handleExtracted(reader, startElement);
        } else if (metadataName.equals(startName)) {
          handleMetadata(reader, startElement);
        } else if (similarName.equals(startName)) {
          handleSimilar(reader, startElement);
        } else if (relevanceInfoName.equals(startName)) {
          handleRelevanceInfo(reader, startElement);
        } else {
          break eventType;
        }

        // found result substructure, so cannot be a raw snippet
        if (eventBuf != null) {
          eventBuf = null;
        }

        break eventType;
      case XMLStreamConstants.END_ELEMENT:
        if (resultName.equals(event.asEndElement().getName())) {
          break events;
        }
        break eventType;
    }

    // buffer candidates for a raw snippet
    if (eventBuf != null) {
      eventBuf.add(event);
    }
  }

  // capture raw snippet
  if (eventBuf != null) {
    int first = tempEvents.size();
    tempEvents.addAll(eventBuf);
    addSnippet(new EventRange(first, tempEvents.size()));
  }
}
 
Example 18
Source File: StaxParser.java    From tutorials with MIT License 4 votes vote down vote up
public static List<WebSite> parse(String path) {
    List<WebSite> websites = new ArrayList<WebSite>();
    WebSite website = null;
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    try {
        XMLEventReader reader = xmlInputFactory.createXMLEventReader(new FileInputStream(path));
        while (reader.hasNext()) {
            XMLEvent nextEvent = reader.nextEvent();
            if (nextEvent.isStartElement()) {
                StartElement startElement = nextEvent.asStartElement();
                switch (startElement.getName()
                    .getLocalPart()) {
                case "website":
                    website = new WebSite();
                    Attribute url = startElement.getAttributeByName(new QName("url"));
                    if (url != null) {
                        website.setUrl(url.getValue());
                    }
                    break;
                case "name":
                    nextEvent = reader.nextEvent();
                    website.setName(nextEvent.asCharacters()
                        .getData());
                    break;
                case "category":
                    nextEvent = reader.nextEvent();
                    website.setCategory(nextEvent.asCharacters()
                        .getData());
                    break;
                case "status":
                    nextEvent = reader.nextEvent();
                    website.setStatus(nextEvent.asCharacters()
                        .getData());
                    break;
                }
            }
            if (nextEvent.isEndElement()) {
                EndElement endElement = nextEvent.asEndElement();
                if (endElement.getName()
                    .getLocalPart()
                    .equals("website")) {
                    websites.add(website);
                }
            }
        }
    } catch (XMLStreamException xse) {
        System.out.println("XMLStreamException");
        xse.printStackTrace();
    } catch (FileNotFoundException fnfe) {
        System.out.println("FileNotFoundException");
        fnfe.printStackTrace();
    }
    return websites;
}
 
Example 19
Source File: StaxParser.java    From tutorials with MIT License 4 votes vote down vote up
public List<Tutorial> getAllTutorial() {
    boolean bTitle = false;
    boolean bDescription = false;
    boolean bDate = false;
    boolean bAuthor = false;
    List<Tutorial> tutorials = new ArrayList<Tutorial>();
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile()));
        Tutorial current = null;
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            switch (event.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                StartElement startElement = event.asStartElement();
                String qName = startElement.getName().getLocalPart();
                if (qName.equalsIgnoreCase("tutorial")) {
                    current = new Tutorial();
                    Iterator<Attribute> attributes = startElement.getAttributes();
                    while (attributes.hasNext()) {
                        Attribute currentAt = attributes.next();
                        if (currentAt.getName().toString().equalsIgnoreCase("tutId")) {
                            current.setTutId(currentAt.getValue());
                        } else if (currentAt.getName().toString().equalsIgnoreCase("type")) {
                            current.setType(currentAt.getValue());
                        }
                    }
                } else if (qName.equalsIgnoreCase("title")) {
                    bTitle = true;
                } else if (qName.equalsIgnoreCase("description")) {
                    bDescription = true;
                } else if (qName.equalsIgnoreCase("date")) {
                    bDate = true;
                } else if (qName.equalsIgnoreCase("author")) {
                    bAuthor = true;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                Characters characters = event.asCharacters();
                if (bTitle) {
                    if (current != null) {
                        current.setTitle(characters.getData());
                    }
                    bTitle = false;
                }
                if (bDescription) {
                    if (current != null) {
                        current.setDescription(characters.getData());
                    }
                    bDescription = false;
                }
                if (bDate) {
                    if (current != null) {
                        current.setDate(characters.getData());
                    }
                    bDate = false;
                }
                if (bAuthor) {
                    if (current != null) {
                        current.setAuthor(characters.getData());
                    }
                    bAuthor = false;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                EndElement endElement = event.asEndElement();
                if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) {
                    if (current != null) {
                        tutorials.add(current);
                    }
                }
                break;
            }
        }

    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    }

    return tutorials;
}
 
Example 20
Source File: AbstractXMLEventWriter.java    From jettison with Apache License 2.0 4 votes vote down vote up
public void add(XMLEvent event) throws XMLStreamException {
	if (event.isStartDocument()) {
		streamWriter.writeStartDocument();
	} else if (event.isStartElement()) {
		StartElement element = event.asStartElement();
		QName elQName = element.getName();
		if (elQName.getPrefix().length() > 0
				&& elQName.getNamespaceURI().length() > 0)
			streamWriter.writeStartElement(elQName.getPrefix(), elQName
					.getLocalPart(), elQName.getNamespaceURI());
		else if (elQName.getNamespaceURI().length() > 0)
			streamWriter.writeStartElement(elQName.getNamespaceURI(),
					elQName.getLocalPart());
		else
			streamWriter.writeStartElement(elQName.getLocalPart());

		// Add element namespaces
		Iterator namespaces = element.getNamespaces();
		while (namespaces.hasNext()) {
			Namespace ns = (Namespace) namespaces.next();
			String prefix = ns.getPrefix();
			String nsURI = ns.getNamespaceURI();
			streamWriter.writeNamespace(prefix, nsURI);
		}

		// Add element attributes
		Iterator attris = element.getAttributes();
		while (attris.hasNext()) {
			Attribute attr = (Attribute) attris.next();
			QName atQName = attr.getName();
			String value = attr.getValue();
			if (atQName.getPrefix().length() > 0
					&& atQName.getNamespaceURI().length() > 0)
				streamWriter.writeAttribute(atQName.getPrefix(), atQName
						.getNamespaceURI(), atQName.getLocalPart(), value);
			else if (atQName.getNamespaceURI().length() > 0)
				streamWriter.writeAttribute(atQName.getNamespaceURI(),
						atQName.getLocalPart(), value);
			else
				streamWriter.writeAttribute(atQName.getLocalPart(), value);
		}
	} else if (event.isCharacters()) {
		Characters chars = event.asCharacters();
		streamWriter.writeCharacters(chars.getData());
	} else if (event.isEndElement()) {
		streamWriter.writeEndElement();
	} else if (event.isEndDocument()) {
		streamWriter.writeEndDocument();
	} else {
		throw new XMLStreamException("Unsupported event type: " + event);
	}
}