javax.xml.stream.events.XMLEvent Java Examples

The following examples show how to use javax.xml.stream.events.XMLEvent. 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 Project: JavaMainRepo   Author: JavaSummer   File: AnimalRepository.java    License: Apache License 2.0 6 votes vote down vote up
public static void createNode(XMLEventWriter eventWriter, String name, String value) throws XMLStreamException {
	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
	XMLEvent end = eventFactory.createDTD("\n");
	XMLEvent tab = eventFactory.createDTD("\t");
	// Create Start node
	StartElement sElement = eventFactory.createStartElement("", "", name);
	eventWriter.add(tab);
	eventWriter.add(sElement);
	// Create Content
	Characters characters = eventFactory.createCharacters(value);
	eventWriter.add(characters);
	// Create End node
	EndElement eElement = eventFactory.createEndElement("", "", name);
	eventWriter.add(eElement);
	eventWriter.add(end);
}
 
Example #2
Source Project: JavaMainRepo   Author: JavaSummer   File: EntityRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param eventWriter
 *            .
 * @param name
 *            The name.
 * @param value
 *            The value.
 * @throws XMLStreamException
 *             .
 */
public static void createNode(final XMLEventWriter eventWriter, final String name, final String value)
		throws XMLStreamException {
	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
	XMLEvent end = eventFactory.createDTD("\n");
	XMLEvent tab = eventFactory.createDTD("\t");
	// Create Start node
	StartElement sElement = eventFactory.createStartElement("", "", name);
	eventWriter.add(tab);
	eventWriter.add(sElement);
	// Create Content
	Characters characters = eventFactory.createCharacters(value);
	eventWriter.add(characters);
	// Create End node
	EndElement eElement = eventFactory.createEndElement("", "", name);
	eventWriter.add(eElement);
	eventWriter.add(end);
}
 
Example #3
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: StAXEvent2SAX.java    License: MIT License 6 votes vote down vote up
private void handleStartDocument(final XMLEvent event) throws SAXException {
    _sax.setDocumentLocator(new Locator2() {
        public int getColumnNumber() {
            return event.getLocation().getColumnNumber();
        }
        public int getLineNumber() {
            return event.getLocation().getLineNumber();
        }
        public String getPublicId() {
            return event.getLocation().getPublicId();
        }
        public String getSystemId() {
            return event.getLocation().getSystemId();
        }
        public String getXMLVersion(){
            return version;
        }
        public String getEncoding(){
            return encoding;
        }

    });
    _sax.startDocument();
}
 
Example #4
Source Project: TencentKona-8   Author: Tencent   File: EventFilterSupport.java    License: GNU General Public License v2.0 6 votes vote down vote up
public XMLEvent nextEvent()throws XMLStreamException{
    if(super.hasNext()){
        //get the next event by calling XMLEventReader
        XMLEvent event = super.nextEvent();

        //if this filter accepts this event then return this event
        if(fEventFilter.accept(event)){
            return event;
        }
        else{
            return nextEvent();
        }
    }else{
        throw new NoSuchElementException();
    }
}
 
Example #5
Source Project: maven-framework-project   Author: v5developer   File: StaxXmlUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 基于迭代模型的方式解析XML
 */
@Test
public void iteratorParseXML() throws Exception {
	XMLInputFactory factory = XMLInputFactory.newInstance();
	InputStream is = ClassLoader.getSystemResourceAsStream("books.xml");
	XMLEventReader reader = factory.createXMLEventReader(is);
	int iteratorNum = 0; //统计遍历的次数
	while(reader.hasNext()) {
		XMLEvent event = reader.nextEvent();
		if(event.isStartElement()) {                                   //通过XMLEvent判断节点类型
			String name = event.asStartElement().getName().toString(); //通过event.asxxx转换节点
			if(name.equals("title")) {
				System.out.print("书籍[" + reader.getElementText() + "]");
			}
			if(name.equals("price")) {
				System.out.println("的价格为[" + reader.getElementText() + "]");
			}
		}
		iteratorNum++;
	}
	is.close();
	System.out.println("本次操作遍历XML的次数合计为[" + iteratorNum + "]次");
}
 
Example #6
Source Project: gama   Author: gama-platform   File: FileSourceGEXF.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * <pre>
 * name 		: THICKNESS
 * attributes 	: THICKNESSAttribute { VALUE!, START, STARTOPEN, END, ENDOPEN }
 * structure 	: SPELLS ?
 * </pre>
 */
private void __thickness(final String edgeId) throws IOException, XMLStreamException {
	XMLEvent e;
	EnumMap<THICKNESSAttribute, String> attributes;

	e = getNextEvent();
	checkValid(e, XMLEvent.START_ELEMENT, "thickness");

	attributes = getAttributes(THICKNESSAttribute.class, e.asStartElement());

	checkRequiredAttributes(e, attributes, THICKNESSAttribute.VALUE);

	e = getNextEvent();

	if (isEvent(e, XMLEvent.START_ELEMENT, "spells")) {
		pushback(e);

		__spells();
		e = getNextEvent();
	}

	checkValid(e, XMLEvent.END_ELEMENT, "thickness");
}
 
Example #7
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: XMLStreamFilterImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
private int findNextEvent() throws XMLStreamException {
    fStreamAdvancedByHasNext = false;
    while(fStreamReader.hasNext()){
        fCurrentEvent = fStreamReader.next();
        if(fStreamFilter.accept(fStreamReader)){
            fEventAccepted = true;
            return fCurrentEvent;
        }
    }
    //although it seems that IllegalStateException should be thrown when next() is called
    //on a stream that has no more items, we have to assume END_DOCUMENT is always accepted
    //in order to pass the TCK
    if (fCurrentEvent == XMLEvent.END_DOCUMENT)
        return fCurrentEvent;
    else
        return -1;
}
 
Example #8
Source Project: vespa   Author: vespa-engine   File: VespaRecordWriter.java    License: 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 #9
Source Project: JavaMainRepo   Author: JavaSummer   File: EmployeeRepository.java    License: Apache License 2.0 6 votes vote down vote up
public static void createNode(XMLEventWriter eventWriter, String name, String value) throws XMLStreamException {
	XMLEventFactory eventFactory = XMLEventFactory.newInstance();
	XMLEvent end = eventFactory.createDTD("\n");
	XMLEvent tab = eventFactory.createDTD("\t");
	// Create Start node
	StartElement sElement = eventFactory.createStartElement("", "", name);
	eventWriter.add(tab);
	eventWriter.add(sElement);
	// Create Content
	Characters characters = eventFactory.createCharacters(value);
	eventWriter.add(characters);
	// Create End node
	EndElement eElement = eventFactory.createEndElement("", "", name);
	eventWriter.add(eElement);
	eventWriter.add(end);
}
 
Example #10
Source Project: openjdk-8   Author: bpupadhyaya   File: StAXFilteredEvent.java    License: GNU General Public License v2.0 6 votes vote down vote up
public String getElementText() throws XMLStreamException
{
    StringBuffer buffer = new StringBuffer();
    XMLEvent e = nextEvent();
    if (!e.isStartElement())
        throw new XMLStreamException(
        CommonResourceBundle.getInstance().getString("message.mustBeOnSTART_ELEMENT"));

    while(hasNext()) {
        e = nextEvent();
        if(e.isStartElement())
            throw new XMLStreamException(
            CommonResourceBundle.getInstance().getString("message.getElementTextExpectTextOnly"));
        if(e.isCharacters())
            buffer.append(((Characters) e).getData());
        if(e.isEndElement())
            return buffer.toString();
    }
    throw new XMLStreamException(CommonResourceBundle.getInstance().getString("message.END_ELEMENTnotFound"));
}
 
Example #11
Source Project: java-technology-stack   Author: codeEngraver   File: Jaxb2XmlDecoder.java    License: MIT License 6 votes vote down vote up
@Override
public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	Flux<XMLEvent> xmlEventFlux = this.xmlEventDecoder.decode(
			inputStream, ResolvableType.forClass(XMLEvent.class), mimeType, hints);

	Class<?> outputClass = elementType.toClass();
	QName typeName = toQName(outputClass);
	Flux<List<XMLEvent>> splitEvents = split(xmlEventFlux, typeName);

	return splitEvents.map(events -> {
		Object value = unmarshal(events, outputClass);
		LogFormatUtils.traceDebug(logger, traceOn -> {
			String formatted = LogFormatUtils.formatValue(value, !traceOn);
			return Hints.getLogPrefix(hints) + "Decoded [" + formatted + "]";
		});
		return value;
	});
}
 
Example #12
Source Project: bazel   Author: bazelbuild   File: AttrXmlResourceValue.java    License: Apache License 2.0 6 votes vote down vote up
private static Map<String, String> readSubValues(XMLEventReader reader, QName subTagType)
    throws XMLStreamException {
  ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
  while (reader.hasNext()
      && XmlResourceValues.isTag(XmlResourceValues.peekNextTag(reader), subTagType)) {
    StartElement element = reader.nextEvent().asStartElement();
    builder.put(
        XmlResourceValues.getElementName(element), XmlResourceValues.getElementValue(element));
    XMLEvent endTag = reader.nextEvent();
    if (!XmlResourceValues.isEndTag(endTag, subTagType)) {
      throw new XMLStreamException(
          String.format("Unexpected [%s]; Expected %s", endTag, "</enum>"), endTag.getLocation());
    }
  }
  return builder.build();
}
 
Example #13
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: XMLDocumentScannerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void reset(PropertyManager propertyManager) {
    super.reset(propertyManager);
    // other settings
    fDoctypeName = null;
    fDoctypePublicId = null;
    fDoctypeSystemId = null;
    fSeenDoctypeDecl = false;
    fNamespaceContext.reset();
    fSupportDTD = ((Boolean)propertyManager.getProperty(XMLInputFactory.SUPPORT_DTD)).booleanValue();

    // xerces features
    fLoadExternalDTD = !((Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.IGNORE_EXTERNAL_DTD)).booleanValue();
    setScannerState(XMLEvent.START_DOCUMENT);
    setDriver(fXMLDeclDriver);
    fSeenInternalSubset = false;
    if(fDTDScanner != null){
        ((XMLDTDScannerImpl)fDTDScanner).reset(propertyManager);
    }
    fEndPos = 0;
    fStartPos = 0;
    if(fDTDDecl != null){
        fDTDDecl.clear();
    }

}
 
Example #14
Source Project: zap-extensions   Author: zaproxy   File: UploadActionListener.java    License: Apache License 2.0 6 votes vote down vote up
public static Boolean reportIsEmpty(File reportFile) throws IOException, XMLStreamException {
	BufferedReader br = Files.newBufferedReader(reportFile.toPath());
	try {
		XMLEventReader reader = xmlInputFactory.createXMLEventReader(br);

		while(reader.hasNext()) {
			XMLEvent event = reader.nextEvent();
			if(event.isStartElement() && !event.asStartElement().getName().getLocalPart().equals("OWASPZAPReport")) {
				return false;
			}
		}
	} finally {
		br.close();
	}
	return true;
}
 
Example #15
Source Project: WikipediaEntities   Author: kno10   File: ParseWikipedia.java    License: 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 Project: openjdk-jdk9   Author: AdoptOpenJDK   File: XMLStreamReaderImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
final static String getEventTypeString(int eventType) {
    switch (eventType) {
        case XMLEvent.START_ELEMENT:
            return "START_ELEMENT";
        case XMLEvent.END_ELEMENT:
            return "END_ELEMENT";
        case XMLEvent.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLEvent.CHARACTERS:
            return "CHARACTERS";
        case XMLEvent.COMMENT:
            return "COMMENT";
        case XMLEvent.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLEvent.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLEvent.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLEvent.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLEvent.DTD:
            return "DTD";
        case XMLEvent.CDATA:
            return "CDATA";
        case XMLEvent.SPACE:
            return "SPACE";
    }
    return "UNKNOWN_EVENT_TYPE, " + String.valueOf(eventType);
}
 
Example #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: ListBasedXMLEventReader.java    License: MIT License 5 votes vote down vote up
@Override
public XMLEvent nextEvent() {
	if (hasNext()) {
		this.currentEvent = this.events.get(this.cursor);
		this.cursor++;
		return this.currentEvent;
	}
	else {
		throw new NoSuchElementException();
	}
}
 
Example #18
Source Project: openjdk-8-source   Author: keerath   File: XMLStreamFilterImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @throws XMLStreamException
 * @return
 */
public int nextTag() throws XMLStreamException {
    if (fStreamAdvancedByHasNext && fEventAccepted &&
            (fCurrentEvent == XMLEvent.START_ELEMENT || fCurrentEvent == XMLEvent.START_ELEMENT)) {
        fStreamAdvancedByHasNext = false;
        return fCurrentEvent;
    }

    int event = findNextTag();
    if (event != -1) {
        return event;
    }
    throw new IllegalStateException("The stream reader has reached the end of the document, or there are no more "+
                                " items to return");
}
 
Example #19
Source Project: hottub   Author: dsrg-uoft   File: XMLStreamReaderImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Returns the namespace of the attribute at the provided
 * index
 * @param index the position of the attribute
 * @return the namespace URI (can be null)
 * @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
 */
public String getAttributeNamespace(int index) {
    //State should be either START_ELEMENT or ATTRIBUTE
    if( fEventType == XMLEvent.START_ELEMENT || fEventType == XMLEvent.ATTRIBUTE) {
        return fScanner.getAttributeIterator().getURI(index);
    } else{
        throw new java.lang.IllegalStateException("Current state is not among the states "
                 + getEventTypeString(XMLEvent.START_ELEMENT) + " , "
                 + getEventTypeString(XMLEvent.ATTRIBUTE)
                 + "valid for getAttributeNamespace()") ;
    }

}
 
Example #20
Source Project: Bytecoder   Author: mirkosertic   File: XMLStreamReaderImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws XMLStreamException
 * @return
 */
public boolean hasNext() throws XMLStreamException {
    //the scanner returns -1 when it detects a broken stream
    if (fEventType == -1) {
        return false;
    }
    //we can check in scanners if the scanner state is not set to
    //terminating, we still have more events.
    return fEventType != XMLEvent.END_DOCUMENT;
}
 
Example #21
Source Project: Bytecoder   Author: mirkosertic   File: XMLStreamReaderImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return
 */
public String getValue() {
    if (fEventType == XMLEvent.PROCESSING_INSTRUCTION) {
        return fScanner.getPIData().toString();
    } else if (fEventType == XMLEvent.COMMENT) {
        return fScanner.getComment();
    } else if (fEventType == XMLEvent.START_ELEMENT || fEventType == XMLEvent.END_ELEMENT) {
        return fScanner.getElementQName().localpart;
    } else if (fEventType == XMLEvent.CHARACTERS) {
        return fScanner.getCharacterData().toString();
    }
    return null;
}
 
Example #22
Source Project: java-technology-stack   Author: codeEngraver   File: ListBasedXMLEventReader.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public XMLEvent peek() {
	if (hasNext()) {
		return this.events.get(this.cursor);
	}
	else {
		return null;
	}
}
 
Example #23
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: StAXSource.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Creates a new instance of a <code>StAXSource</code>
 * by supplying an {@link XMLEventReader}.</p>
 *
 * <p><code>XMLEventReader</code> must be a
 * non-<code>null</code> reference.</p>
 *
 * <p><code>XMLEventReader</code> must be in
 * {@link XMLStreamConstants#START_DOCUMENT} or
 * {@link XMLStreamConstants#START_ELEMENT} state.</p>
 *
 * @param xmlEventReader <code>XMLEventReader</code> used to create
 *   this <code>StAXSource</code>.
 *
 * @throws XMLStreamException If <code>xmlEventReader</code> access
 *   throws an <code>Exception</code>.
 * @throws IllegalArgumentException If <code>xmlEventReader</code> ==
 *   <code>null</code>.
 * @throws IllegalStateException If <code>xmlEventReader</code>
 *   is not in <code>XMLStreamConstants.START_DOCUMENT</code> or
 *   <code>XMLStreamConstants.START_ELEMENT</code> state.
 */
public StAXSource(final XMLEventReader xmlEventReader)
    throws XMLStreamException {

    if (xmlEventReader == null) {
        throw new IllegalArgumentException(
                "StAXSource(XMLEventReader) with XMLEventReader == null");
    }

    // TODO: This is ugly ...
    // there is no way to know the current position(event) of
    // XMLEventReader.  peek() is the only way to know the next event.
    // The next event on the input stream should be
    // XMLStreamConstants.START_DOCUMENT or
    // XMLStreamConstants.START_ELEMENT.
    XMLEvent event = xmlEventReader.peek();
    int eventType = event.getEventType();
    if (eventType != XMLStreamConstants.START_DOCUMENT
            && eventType != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException(
            "StAXSource(XMLEventReader) with XMLEventReader "
            + "not in XMLStreamConstants.START_DOCUMENT or "
            + "XMLStreamConstants.START_ELEMENT state");
    }

    this.xmlEventReader = xmlEventReader;
    systemId = event.getLocation().getSystemId();
}
 
Example #24
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: HasNextTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private HasNextTypeFilter createFilter() {

        HasNextTypeFilter f = new HasNextTypeFilter();

        f.addType(XMLEvent.START_ELEMENT);
        f.addType(XMLEvent.END_ELEMENT);
        f.addType(XMLEvent.PROCESSING_INSTRUCTION);
        f.addType(XMLEvent.CHARACTERS);
        f.addType(XMLEvent.COMMENT);
        f.addType(XMLEvent.SPACE);
        f.addType(XMLEvent.START_DOCUMENT);
        f.addType(XMLEvent.END_DOCUMENT);
        return f;
    }
 
Example #25
Source Project: gama   Author: gama-platform   File: FileSourceGraphML.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * <pre>
 * <!ELEMENT graphml  ((desc)?,(key)*,((data)|(graph))*)>
 * </pre>
 *
 * @throws IOException
 * @throws XMLStreamException
 */
private void __graphml() throws IOException, XMLStreamException {
	XMLEvent e;

	e = getNextEvent();
	checkValid(e, XMLEvent.START_ELEMENT, "graphml");

	e = getNextEvent();

	if (isEvent(e, XMLEvent.START_ELEMENT, "desc")) {
		pushback(e);
		__desc();

		e = getNextEvent();
	}

	while (isEvent(e, XMLEvent.START_ELEMENT, "key")) {
		pushback(e);
		__key();

		e = getNextEvent();
	}

	while (isEvent(e, XMLEvent.START_ELEMENT, "data") || isEvent(e, XMLEvent.START_ELEMENT, "graph")) {
		pushback(e);

		if (isEvent(e, XMLEvent.START_ELEMENT, "data")) {
			__data();
		} else {
			__graph();
		}

		e = getNextEvent();
	}

	checkValid(e, XMLEvent.END_ELEMENT, "graphml");
}
 
Example #26
Source Project: tidy-maven-plugin   Author: mojohaus   File: EnsureOrderAndIndent.java    License: Apache License 2.0 5 votes vote down vote up
private String formatSection( XMLEventReader reader, String pom, Format format )
    throws XMLStreamException
{
    int startOfSection = getPosOfNextEvent( reader );
    int[] starts = new int[sequence.size()];
    int[] ends = new int[sequence.size()];
    XMLEvent endScope = calculateStartsAndEnds( reader, starts, ends );
    return formatSection( reader, pom, format, startOfSection, starts, ends, endScope );
}
 
Example #27
Source Project: java-client-api   Author: marklogic   File: Utilities.java    License: Apache License 2.0 5 votes vote down vote up
public static String eventsToString(List<XMLEvent> events) {
  byte[] bytes = eventsToBytes(events);
  if (bytes == null || bytes.length == 0) {
    return null;
  }

  return new String(bytes, Charset.forName("UTF-8"));
}
 
Example #28
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: StAXSource.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Creates a new instance of a <code>StAXSource</code>
 * by supplying an {@link XMLEventReader}.</p>
 *
 * <p><code>XMLEventReader</code> must be a
 * non-<code>null</code> reference.</p>
 *
 * <p><code>XMLEventReader</code> must be in
 * {@link XMLStreamConstants#START_DOCUMENT} or
 * {@link XMLStreamConstants#START_ELEMENT} state.</p>
 *
 * @param xmlEventReader <code>XMLEventReader</code> used to create
 *   this <code>StAXSource</code>.
 *
 * @throws XMLStreamException If <code>xmlEventReader</code> access
 *   throws an <code>Exception</code>.
 * @throws IllegalArgumentException If <code>xmlEventReader</code> ==
 *   <code>null</code>.
 * @throws IllegalStateException If <code>xmlEventReader</code>
 *   is not in <code>XMLStreamConstants.START_DOCUMENT</code> or
 *   <code>XMLStreamConstants.START_ELEMENT</code> state.
 */
public StAXSource(final XMLEventReader xmlEventReader)
    throws XMLStreamException {

    if (xmlEventReader == null) {
        throw new IllegalArgumentException(
                "StAXSource(XMLEventReader) with XMLEventReader == null");
    }

    // TODO: This is ugly ...
    // there is no way to know the current position(event) of
    // XMLEventReader.  peek() is the only way to know the next event.
    // The next event on the input stream should be
    // XMLStreamConstants.START_DOCUMENT or
    // XMLStreamConstants.START_ELEMENT.
    XMLEvent event = xmlEventReader.peek();
    int eventType = event.getEventType();
    if (eventType != XMLStreamConstants.START_DOCUMENT
            && eventType != XMLStreamConstants.START_ELEMENT) {
        throw new IllegalStateException(
            "StAXSource(XMLEventReader) with XMLEventReader "
            + "not in XMLStreamConstants.START_DOCUMENT or "
            + "XMLStreamConstants.START_ELEMENT state");
    }

    this.xmlEventReader = xmlEventReader;
    systemId = event.getLocation().getSystemId();
}
 
Example #29
Source Project: olingo-odata4   Author: apache   File: MetadataParser.java    License: Apache License 2.0 5 votes vote down vote up
private String elementValue(XMLEventReader reader, StartElement element) throws XMLStreamException {
  while (reader.hasNext()) {
    XMLEvent event = reader.peek();
    if (event.isStartElement() || event.isEndElement()) {
      return null;
    } else if (event.isCharacters()){
      reader.nextEvent();
      String data = event.asCharacters().getData();
      if (data.trim().length() > 0) {
        return data.trim();
      }
    }
  }    
  return null;
}
 
Example #30
Source Project: JDKSourceCode1.8   Author: wupeixuan   File: XMLStreamReaderImpl.java    License: MIT License 5 votes vote down vote up
/**
 * @return
 */
public String getNamespaceURI() {
    //doesn't take care of Attribute as separte event
    if(fEventType == XMLEvent.START_ELEMENT || fEventType == XMLEvent.END_ELEMENT){
        return fScanner.getElementQName().uri ;
    }
    return null ;
}