本文整理汇总了Java中javax.xml.stream.XMLEventReader.nextEvent方法的典型用法代码示例。如果您正苦于以下问题:Java XMLEventReader.nextEvent方法的具体用法?Java XMLEventReader.nextEvent怎么用?Java XMLEventReader.nextEvent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.xml.stream.XMLEventReader
的用法示例。
在下文中一共展示了XMLEventReader.nextEvent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: test
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
@Test
public void test() {
String xmlData = "<?xml version=\"1.0\"?><Test>Hello</Test>";
try {
XMLEventReader xmlReader = XMLInputFactory.newInstance().createXMLEventReader(new ByteArrayInputStream(xmlData.getBytes()));
XMLEvent event = xmlReader.nextEvent();
System.out.println(event.getClass());
// xmlReader.peek(); // error in both cases with/without peek()
event = xmlReader.nextTag(); // nextEvent() would work fine
// nextTag() forgets to set fLastEvent
System.out.println(event.getClass());
String text = xmlReader.getElementText();
System.out.println(text);
} catch (XMLStreamException e) {
Assert.fail(e.getMessage());
}
}
示例2: testCR6419687
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
/**
* Test: 6419687 NPE in XMLEventWriterImpl.
*/
@Test
public void testCR6419687() {
try {
InputStream in = getClass().getResourceAsStream("ReaderToWriterTest.wsdl");
OutputStream out = new FileOutputStream(USER_DIR + "ReaderToWriterTest-out.xml");
XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(in);
XMLEventWriter writer = XML_OUTPUT_FACTORY.createXMLEventWriter(out, "UTF-8");
while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();
writer.add(event);
}
reader.close();
writer.close();
} catch (XMLStreamException xmlStreamException) {
xmlStreamException.printStackTrace();
Assert.fail(xmlStreamException.toString());
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
Assert.fail(fileNotFoundException.toString());
}
}
示例3: getCharacterData
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
/**
* Reads the data from the {@link XMLEvent} and returns it. CData
* will be handled special.
* @param event {@link XMLEvent}
* @param eventReader Reader for Reading {@link XMLEvent}
* @return Character data from element
* @throws XMLStreamException
*/
private String getCharacterData(XMLEvent event, final XMLEventReader eventReader) throws XMLStreamException {
String result = "";
event = eventReader.nextEvent();
if (event instanceof Characters) {
result = event.asCharacters().getData();
}
return result;
}
示例4: readXMLByStAX
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
public static void readXMLByStAX() throws XMLStreamException, FileNotFoundException {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(new FileInputStream("test.xml"));//StaxDemo.class.getResourceAsStream("test.xml")
XMLEvent event;
StringBuffer parsingResult = new StringBuffer();
while (reader.hasNext()) {
event = reader.nextEvent();
if (event.isStartElement()) {
StartElement se = event.asStartElement();
parsingResult.append("<");
parsingResult.append(se.getName());
if (se.getName().getLocalPart().equals("catalog")) {
parsingResult.append("id=");
parsingResult.append(se.getAttributeByName(new QName("id")).getValue());
parsingResult.append("");
}
parsingResult.append(">");
} else if (event.isCharacters()) {
parsingResult.append(event.asCharacters().getData());
} else if (event.isEndElement()) {
parsingResult.append("</");
parsingResult.append(event.asEndElement().getName());
parsingResult.append(">");
}
}
System.out.println(parsingResult);
}
示例5: handleMissingField
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
private void handleMissingField(String fieldName, XMLEventReader parser,
XMLEvent event, ExtensionRegistry extensionRegistry,
UnknownFieldSet.Builder builder) throws XMLStreamException {
// skip over the unknown fields, since we can't map them by id, then this message must not know about them.
// We 'could' map them into the UnknownFieldSet, however none of the other formatters support this..
// but in the future it would probably be useful for the case: Message A (v2) -> Message B (v1) -> Xml -> Message A (v2)
// this would require extra meta data in the xml to know the type of the unknown-field.
if (event.isStartElement()) {
/**
* This loop will eat up everything inside "6"
* So when this method is called, fieldName = 6, and event is set at index="11"
* <unknown-field index="6">
* <unknown-field index="11">566667</unknown-field>
* <unknown-field index="15">
* <unknown-field index="16">566667</unknown-field>
* </unknown-field>
* </unknown-field>
*/
int depth = 1; // we start 1 level down, the value of "6"
while (parser.hasNext()) {
XMLEvent nextEvent = parser.nextEvent();
if (nextEvent.isEndElement()) {
depth--;
if (depth <= 0 && parser.peek().isEndElement()) {
break;
}
} else if (nextEvent.isStartElement()) {
depth++;
}
}
} else if (event.isCharacters()) {
// done, let it slide.
}
}
示例6: testNextEvent
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
private static void testNextEvent(int max)
throws IOException, XMLStreamException {
System.out.println("\nTest nextEvent (" + max + ")...");
XMLEventReader reader = createXmlReader(max);
XMLEvent event;
do {
event = reader.nextEvent();
System.out.println(event);
} while (event.getEventType() != XMLEvent.END_DOCUMENT);
System.out.println("nextEvent passed\n");
}
示例7: testDTDEvent
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
/**
* DTDEvent instances constructed via event reader are missing the notation
* and entity declaration information
*/
@Test
public void testDTDEvent() {
String XML = "<?xml version='1.0' ?>" + "<!DOCTYPE root [\n" + "<!ENTITY intEnt 'internal'>\n" + "<!ENTITY extParsedEnt SYSTEM 'url:dummy'>\n"
+ "<!NOTATION notation PUBLIC 'notation-public-id'>\n" + "<!NOTATION notation2 SYSTEM 'url:dummy'>\n"
+ "<!ENTITY extUnparsedEnt SYSTEM 'url:dummy2' NDATA notation>\n" + "]>" + "<root />";
try {
XMLEventReader er = getReader(XML);
XMLEvent evt = er.nextEvent(); // StartDocument
evt = er.nextEvent(); // DTD
if (evt.getEventType() != XMLStreamConstants.DTD) {
Assert.fail("Expected DTD event");
}
DTD dtd = (DTD) evt;
List entities = dtd.getEntities();
if (entities == null) {
Assert.fail("No entity found. Expected 3.");
} else {
Assert.assertEquals(entities.size(), 3);
}
// Let's also verify they are all of right type...
testListElems(entities, EntityDeclaration.class);
List notations = dtd.getNotations();
if (notations == null) {
Assert.fail("No notation found. Expected 2.");
} else {
Assert.assertEquals(notations.size(), 2);
}
// Let's also verify they are all of right type...
testListElems(notations, NotationDeclaration.class);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
示例8: unmarshal
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
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;
}
示例9: testEventReader
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
@Test(dataProvider = "xml-data")
public void testEventReader(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception {
XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true);
if (chunkSize > 0) {
xif.setProperty(CDATA_CHUNK_SIZE, chunkSize);
}
XMLEventReader reader = xif.createXMLEventReader(new StringReader(xml));
StringBuilder cdata = new StringBuilder();
int numOfChunks = 0;
boolean isWithinLimit = true;
while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();
//All text events get reported as Characters events
if (event.getEventType() == XMLStreamConstants.CHARACTERS) {
Characters cdataEvent = (Characters) event;
if (cdataEvent.isCData()) {
String text = cdataEvent.getData();
numOfChunks++;
if (text.length() > chunkSize) {
isWithinLimit = false;
}
debugPrint("\nCDATA: " + text.length());
cdata.append(text);
}
}
}
debugPrint("CData in single chunk:" + cdata.toString().length());
Assert.assertEquals(numOfChunks, expectedNumOfChunks);
Assert.assertEquals(isWithinLimit, withinLimit);
}
示例10: unmarshalModel
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
/**
* See {@link PolicyModelUnmarshaller#unmarshalModel(Object) base method documentation}.
*/
public PolicySourceModel unmarshalModel(final Object storage) throws PolicyException {
final XMLEventReader reader = createXMLEventReader(storage);
PolicySourceModel model = null;
loop:
while (reader.hasNext()) {
try {
final XMLEvent event = reader.peek();
switch (event.getEventType()) {
case XMLStreamConstants.START_DOCUMENT:
case XMLStreamConstants.COMMENT:
reader.nextEvent();
break; // skipping the comments and start document events
case XMLStreamConstants.CHARACTERS:
processCharacters(ModelNode.Type.POLICY, event.asCharacters(), null);
// we advance the reader only if there is no exception thrown from
// the processCharacters(...) call. Otherwise we don't modify the stream
reader.nextEvent();
break;
case XMLStreamConstants.START_ELEMENT:
if (NamespaceVersion.resolveAsToken(event.asStartElement().getName()) == XmlToken.Policy) {
StartElement rootElement = reader.nextEvent().asStartElement();
model = initializeNewModel(rootElement);
unmarshalNodeContent(model.getNamespaceVersion(), model.getRootNode(), rootElement.getName(), reader);
break loop;
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
}
default:
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
}
} catch (XMLStreamException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
}
}
return model;
}
示例11: addMenu
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
void addMenu(XMLEventReader xer, XMLEvent event) throws XMLStreamException {
// user did not submit this part of code, just jump to the end of menu
// element
int eventType = 0;
while (true) {
event = xer.nextEvent();
// System.out.println("event: " + event);
eventType = event.getEventType();
if (eventType == XMLStreamConstants.END_ELEMENT && event.asEndElement().getName().equals(new QName("menu"))) {
break;
}
}
}
示例12: writeEvents
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
private void writeEvents(XMLEventReader reader, XMLEventWriter writer) throws XMLStreamException {
while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();
writer.add(event);
}
reader.close();
writer.close();
}
示例13: processStartTag
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
private void processStartTag(final StartElement element, final StartElement parent,
final XMLEventReader reader, final Map<URI, Policy> map)
throws PolicyException {
try {
final QName name = element.getName();
if (parent == null) {
if (!name.equals(POLICIES)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<Policies>", name, element.getLocation())));
}
} else {
final QName parentName = parent.getName();
if (parentName.equals(POLICIES)) {
if (!name.equals(POLICY_ATTACHMENT)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<PolicyAttachment>", name, element.getLocation())));
}
} else if (parentName.equals(POLICY_ATTACHMENT)) {
if (name.equals(POLICY)) {
readPolicy(reader);
return;
} else if (!name.equals(APPLIES_TO)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<AppliesTo> or <Policy>", name, element.getLocation())));
}
} else if (parentName.equals(APPLIES_TO)) {
if (!name.equals(URI)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<URI>", name, element.getLocation())));
}
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0090_UNEXPECTED_ELEMENT(name, element.getLocation())));
}
}
reader.nextEvent();
this.unmarshal(reader, element);
} catch (XMLStreamException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(element.getLocation()), e));
}
}
示例14: testEventReader
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
@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());
}
}
示例15: readTestResults
import javax.xml.stream.XMLEventReader; //导入方法依赖的package包/类
private static Collection<TestResult> readTestResults(XMLEventReader eventReader) throws XMLStreamException {
final Set<TestResult> testResults = new HashSet<>();
TestResult currentTestResult = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
final StartElement startElement = event.asStartElement();
if ("testcase".equalsIgnoreCase(startElement.getName().getLocalPart())) {
// Read attributes
String name = null, classname = null;
Status status = null;
final Iterator<Attribute> attributes = startElement.getAttributes();
while (attributes.hasNext()) {
final Attribute attribute = attributes.next();
if ("classname".equalsIgnoreCase(attribute.getName().toString())) {
classname = attribute.getValue();
}
if ("name".equalsIgnoreCase(attribute.getName().toString())) {
name = attribute.getValue();
}
}
currentTestResult = new TestResult(classname, name, Status.PASSED);
}
if ("failure".equalsIgnoreCase(startElement.getName().getLocalPart())) {
currentTestResult.setStatus(Status.FAILURE);
}
if ("error".equalsIgnoreCase(startElement.getName().getLocalPart())) {
currentTestResult.setStatus(Status.ERROR);
}
if ("skipped".equalsIgnoreCase(startElement.getName().getLocalPart())) {
currentTestResult.setStatus(Status.SKIPPED);
}
if ("rerunFailure".equalsIgnoreCase(startElement.getName().getLocalPart())) {
currentTestResult.setStatus(Status.RE_RUN_FAILURE);
}
}
if (event.isEndElement()) {
final EndElement endElementElement = event.asEndElement();
if ("testcase".equalsIgnoreCase(endElementElement.getName().getLocalPart())) {
testResults.add(currentTestResult);
}
}
}
return testResults;
}