List of usage examples for javax.xml.stream XMLStreamReader getNamespacePrefix
public String getNamespacePrefix(int index);
From source file:com.prowidesoftware.swift.io.parser.MxParser.java
/** * Takes an xml with an MX message and detects the specific message type * parsing just the namespace from the Document element. If the Document * element is not present, or without the namespace or if the namespace url * contains invalid content it will return null. * <br><br>/*from w w w . j a v a 2 s.com*/ * Example of a recognizable Document element:<br> * <Doc:Document xmlns:Doc="urn:swift:xsd:camt.003.001.04" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> * <br> * The implementation is intended to be lightweight and efficient, based on {@link javax.xml.stream.XMLStreamReader} * * @return id with the detected MX message type or null if it cannot be determined. * @since 7.7 */ public MxId detectMessage() { if (StringUtils.isBlank(this.buffer)) { log.log(Level.SEVERE, "cannot detect message from null or empty content"); return null; } final javax.xml.stream.XMLInputFactory xif = javax.xml.stream.XMLInputFactory.newInstance(); try { final javax.xml.stream.XMLStreamReader reader = xif .createXMLStreamReader(new StringReader(this.buffer)); while (reader.hasNext()) { int event = reader.next(); if (javax.xml.stream.XMLStreamConstants.START_ELEMENT == event && reader.getLocalName().equals(DOCUMENT_LOCALNAME)) { if (reader.getNamespaceCount() > 0) { //log.finest("ELEMENT START: " + reader.getLocalName() + " , namespace count is: " + reader.getNamespaceCount()); for (int nsIndex = 0; nsIndex < reader.getNamespaceCount(); nsIndex++) { final String nsPrefix = StringUtils.trimToNull(reader.getNamespacePrefix(nsIndex)); final String elementPrefix = StringUtils.trimToNull(reader.getPrefix()); if (StringUtils.equals(nsPrefix, elementPrefix)) { String nsId = reader.getNamespaceURI(nsIndex); //log.finest("\tNamepsace prefix: " + nsPrefix + " associated with URI " + nsId); return new MxId(nsId); } } } } } } catch (final Exception e) { log.log(Level.SEVERE, "error while detecting message", e); } return null; }
From source file:com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor.java
@Override public void readObjectsIteratively(@NotNull ParserSource source, @NotNull ParsingContext parsingContext, RootXNodeHandler handler) throws SchemaException, IOException { InputStream is = source.getInputStream(); XMLStreamReader stream = null; try {//from w w w .ja va 2s . c om stream = XMLInputFactory.newInstance().createXMLStreamReader(is); int eventType = stream.nextTag(); if (eventType != XMLStreamConstants.START_ELEMENT) { throw new SystemException("StAX Malfunction?"); } DOMConverter domConverter = new DOMConverter(); Map<String, String> rootNamespaceDeclarations = new HashMap<>(); QName objectsMarker = schemaRegistry.getPrismContext().getObjectsElementName(); if (objectsMarker != null && !QNameUtil.match(stream.getName(), objectsMarker)) { readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler); } for (int i = 0; i < stream.getNamespaceCount(); i++) { rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i)); } while (stream.hasNext()) { eventType = stream.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (!readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler)) { return; } } } } catch (XMLStreamException ex) { String lineInfo = stream != null ? " on line " + stream.getLocation().getLineNumber() : ""; throw new SchemaException("Exception while parsing XML" + lineInfo + ": " + ex.getMessage(), ex); } finally { if (source.closeStreamAfterParsing()) { IOUtils.closeQuietly(is); } } }
From source file:de.uzk.hki.da.model.ObjectPremisXmlWriter.java
/** * Integrate jhove data./*from w w w.j a va 2s .c om*/ * * @param jhoveFilePath the jhove file path * @param tab the tab * @throws XMLStreamException the xML stream exception * @author Thomas Kleinke * @throws FileNotFoundException */ private void integrateJhoveData(String jhoveFilePath, int tab) throws XMLStreamException, FileNotFoundException { File jhoveFile = new File(jhoveFilePath); if (!jhoveFile.exists()) throw new FileNotFoundException("file does not exist. " + jhoveFile); FileInputStream inputStream = null; inputStream = new FileInputStream(jhoveFile); XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream); boolean textElement = false; while (streamReader.hasNext()) { int event = streamReader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: writer.writeDTD("\n"); indent(tab); tab++; String prefix = streamReader.getPrefix(); if (prefix != null && !prefix.equals("")) { writer.setPrefix(prefix, streamReader.getNamespaceURI()); writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName()); } else writer.writeStartElement(streamReader.getLocalName()); for (int i = 0; i < streamReader.getNamespaceCount(); i++) writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i)); for (int i = 0; i < streamReader.getAttributeCount(); i++) { QName qname = streamReader.getAttributeName(i); String attributeName = qname.getLocalPart(); String attributePrefix = qname.getPrefix(); if (attributePrefix != null && !attributePrefix.equals("")) attributeName = attributePrefix + ":" + attributeName; writer.writeAttribute(attributeName, streamReader.getAttributeValue(i)); } break; case XMLStreamConstants.CHARACTERS: if (!streamReader.isWhiteSpace()) { writer.writeCharacters(streamReader.getText()); textElement = true; } break; case XMLStreamConstants.END_ELEMENT: tab--; if (!textElement) { writer.writeDTD("\n"); indent(tab); } writer.writeEndElement(); textElement = false; break; default: break; } } streamReader.close(); try { inputStream.close(); } catch (IOException e) { throw new RuntimeException("Failed to close input stream", e); } }
From source file:de.uzk.hki.da.cb.CreatePremisAction.java
/** * Accepts a premis.xml file and creates a new xml file for each jhove section * /*from w w w. j a v a 2s.co m*/ * @author Thomas Kleinke * Extract jhove data. * * @param premisFilePath the premis file path * @param outputFolder the output folder * @throws XMLStreamException the xML stream exception */ public void extractJhoveData(String premisFilePath, String outputFolder) throws XMLStreamException { outputFolder += "/premis_output/"; FileInputStream inputStream = null; try { inputStream = new FileInputStream(premisFilePath); } catch (FileNotFoundException e) { throw new RuntimeException("Couldn't find file " + premisFilePath, e); } XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream); boolean textElement = false; boolean jhoveSection = false; boolean objectIdentifierValue = false; int tab = 0; String fileId = ""; while (streamReader.hasNext()) { int event = streamReader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: if (streamReader.getLocalName().equals("jhove")) { jhoveSection = true; String outputFilePath = outputFolder + fileId.replace('/', '_').replace('.', '_') + ".xml"; if (!new File(outputFolder).exists()) new File(outputFolder).mkdirs(); writer = startNewDocument(outputFilePath); } if (streamReader.getLocalName().equals("objectIdentifierValue")) objectIdentifierValue = true; if (jhoveSection) { writer.writeDTD("\n"); indent(tab); tab++; String prefix = streamReader.getPrefix(); if (prefix != null && !prefix.equals("")) { writer.setPrefix(prefix, streamReader.getNamespaceURI()); writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName()); } else writer.writeStartElement(streamReader.getLocalName()); for (int i = 0; i < streamReader.getNamespaceCount(); i++) writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i)); for (int i = 0; i < streamReader.getAttributeCount(); i++) { QName qname = streamReader.getAttributeName(i); String attributeName = qname.getLocalPart(); String attributePrefix = qname.getPrefix(); if (attributePrefix != null && !attributePrefix.equals("")) attributeName = attributePrefix + ":" + attributeName; writer.writeAttribute(attributeName, streamReader.getAttributeValue(i)); } } break; case XMLStreamConstants.CHARACTERS: if (objectIdentifierValue) { fileId = streamReader.getText(); objectIdentifierValue = false; } if (jhoveSection && !streamReader.isWhiteSpace()) { writer.writeCharacters(streamReader.getText()); textElement = true; } break; case XMLStreamConstants.END_ELEMENT: if (jhoveSection) { tab--; if (!textElement) { writer.writeDTD("\n"); indent(tab); } writer.writeEndElement(); textElement = false; if (streamReader.getLocalName().equals("jhove")) { jhoveSection = false; finalizeDocument(); } } break; case XMLStreamConstants.END_DOCUMENT: streamReader.close(); try { inputStream.close(); } catch (IOException e) { throw new RuntimeException("Failed to close input stream", e); } break; default: break; } } }
From source file:com.evolveum.midpoint.common.validator.Validator.java
public void validate(InputStream inputStream, OperationResult validatorResult, String objectResultOperationName) { XMLStreamReader stream = null; try {// w ww.j a v a 2 s .c o m Map<String, String> rootNamespaceDeclarations = new HashMap<String, String>(); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); stream = xmlInputFactory.createXMLStreamReader(inputStream); int eventType = stream.nextTag(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (!stream.getName().equals(SchemaConstants.C_OBJECTS)) { // This has to be an import file with a single objects. Try // to process it. OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName); progress++; objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress); EventResult cont = null; try { cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations, validatorResult); } catch (RuntimeException e) { // Make sure that unexpected error is recorded. objectResult.recordFatalError(e); throw e; } if (!cont.isCont()) { String message = null; if (cont.getReason() != null) { message = cont.getReason(); } else { message = "Object validation failed (no reason given)"; } if (objectResult.isUnknown()) { objectResult.recordFatalError(message); } validatorResult.recordFatalError(message); return; } // return to avoid processing objects in loop validatorResult.computeStatus("Validation failed", "Validation warnings"); return; } // Extract root namespace declarations for (int i = 0; i < stream.getNamespaceCount(); i++) { rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i)); } } else { throw new SystemException("StAX Malfunction?"); } while (stream.hasNext()) { eventType = stream.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName); progress++; objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress); EventResult cont = null; try { // Read and validate individual object from the stream cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations, validatorResult); } catch (RuntimeException e) { if (objectResult.isUnknown()) { // Make sure that unexpected error is recorded. objectResult.recordFatalError(e); } throw e; } if (objectResult.isError()) { errors++; } objectResult.cleanupResult(); validatorResult.summarize(); if (cont.isStop()) { if (cont.getReason() != null) { validatorResult.recordFatalError("Processing has been stopped: " + cont.getReason()); } else { validatorResult.recordFatalError("Processing has been stopped"); } // This means total stop, no other objects will be // processed return; } if (!cont.isCont()) { if (stopAfterErrors > 0 && errors >= stopAfterErrors) { validatorResult.recordFatalError("Too many errors (" + errors + ")"); return; } } } } } catch (XMLStreamException ex) { // validatorResult.recordFatalError("XML parsing error: " + // ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex); validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex); if (handler != null) { handler.handleGlobalError(validatorResult); } return; } // Error count is sufficient. Detailed messages are in subresults validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed"); }
From source file:org.activiti.bpmn.converter.parser.DefinitionsParser.java
@SuppressWarnings("unchecked") public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception { model.setTargetNamespace(xtr.getAttributeValue(null, TARGET_NAMESPACE_ATTRIBUTE)); for (int i = 0; i < xtr.getNamespaceCount(); i++) { String prefix = xtr.getNamespacePrefix(i); if (StringUtils.isNotEmpty(prefix)) { model.addNamespace(prefix, xtr.getNamespaceURI(i)); }/*from w w w . j a v a 2s . co m*/ } for (int i = 0; i < xtr.getAttributeCount(); i++) { ExtensionAttribute extensionAttribute = new ExtensionAttribute(); extensionAttribute.setName(xtr.getAttributeLocalName(i)); extensionAttribute.setValue(xtr.getAttributeValue(i)); if (StringUtils.isNotEmpty(xtr.getAttributeNamespace(i))) { extensionAttribute.setNamespace(xtr.getAttributeNamespace(i)); } if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) { extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i)); } if (!BpmnXMLUtil.isBlacklisted(extensionAttribute, defaultAttributes)) { model.addDefinitionsAttribute(extensionAttribute); } } }
From source file:org.apache.axiom.om.impl.serialize.StreamingOMSerializer.java
/** * @param reader//from w w w . j a va 2 s . co m * @param writer * @throws XMLStreamException */ protected void serializeElement(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { // Note: To serialize the start tag, we must follow the order dictated by the JSR-173 (StAX) specification. // Please keep this code in sync with the code in OMSerializerUtil.serializeStartpart // The algorithm is: // ... generate writeStartElement // // ... generate setPrefix/setDefaultNamespace for each namespace declaration if the prefix is unassociated. // ... generate setPrefix/setDefaultNamespace if the prefix of the element is unassociated // ... generate setPrefix/setDefaultNamespace for each unassociated prefix of the attributes. // // ... generate writeNamespace/writerDefaultNamespace for the new namespace declarations determine during the "set" processing // ... generate writeAttribute for each attribute ArrayList writePrefixList = null; ArrayList writeNSList = null; // Get the prefix and namespace of the element. "" and null are identical. String ePrefix = reader.getPrefix(); ePrefix = (ePrefix != null && ePrefix.length() == 0) ? null : ePrefix; String eNamespace = reader.getNamespaceURI(); eNamespace = (eNamespace != null && eNamespace.length() == 0) ? null : eNamespace; // Write the startElement if required if (eNamespace != null) { if (ePrefix == null) { if (!OMSerializerUtil.isAssociated("", eNamespace, writer)) { if (writePrefixList == null) { writePrefixList = new ArrayList(); writeNSList = new ArrayList(); } writePrefixList.add(""); writeNSList.add(eNamespace); } writer.writeStartElement("", reader.getLocalName(), eNamespace); } else { if (!OMSerializerUtil.isAssociated(ePrefix, eNamespace, writer)) { if (writePrefixList == null) { writePrefixList = new ArrayList(); writeNSList = new ArrayList(); } writePrefixList.add(ePrefix); writeNSList.add(eNamespace); } writer.writeStartElement(ePrefix, reader.getLocalName(), eNamespace); } } else { writer.writeStartElement(reader.getLocalName()); } // Generate setPrefix for the namespace declarations int count = reader.getNamespaceCount(); for (int i = 0; i < count; i++) { String prefix = reader.getNamespacePrefix(i); prefix = (prefix != null && prefix.length() == 0) ? null : prefix; String namespace = reader.getNamespaceURI(i); namespace = (namespace != null && namespace.length() == 0) ? null : namespace; String newPrefix = OMSerializerUtil.generateSetPrefix(prefix, namespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList = new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Generate setPrefix for the element // If the prefix is not associated with a namespace yet, remember it so that we can // write out a namespace declaration String newPrefix = OMSerializerUtil.generateSetPrefix(ePrefix, eNamespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList = new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(eNamespace); } } // Now Generate setPrefix for each attribute count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { String prefix = reader.getAttributePrefix(i); prefix = (prefix != null && prefix.length() == 0) ? null : prefix; String namespace = reader.getAttributeNamespace(i); namespace = (namespace != null && namespace.length() == 0) ? null : namespace; // Default prefix referencing is not allowed on an attribute if (prefix == null && namespace != null) { String writerPrefix = writer.getPrefix(namespace); writerPrefix = (writerPrefix != null && writerPrefix.length() == 0) ? null : writerPrefix; prefix = (writerPrefix != null) ? writerPrefix : generateUniquePrefix(writer.getNamespaceContext()); } newPrefix = OMSerializerUtil.generateSetPrefix(prefix, namespace, writer, true); // If the prefix is not associated with a namespace yet, remember it so that we can // write out a namespace declaration if (newPrefix != null) { if (writePrefixList == null) { writePrefixList = new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Now Generate setPrefix for each prefix referenced in an xsi:type // For example xsi:type="p:dataType" // The following code will make sure that setPrefix is called for "p". count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { String prefix = reader.getAttributePrefix(i); prefix = (prefix != null && prefix.length() == 0) ? null : prefix; String namespace = reader.getAttributeNamespace(i); namespace = (namespace != null && namespace.length() == 0) ? null : namespace; String localName = reader.getAttributeLocalName(i); if (XSI_URI.equals(namespace) && XSI_LOCAL_NAME.equals(localName)) { String value = reader.getAttributeValue(i); if (DEBUG_ENABLED) { log.debug("The value of xsi:type is " + value); } if (value != null) { value = value.trim(); if (value.indexOf(":") > 0) { String refPrefix = value.substring(0, value.indexOf(":")); String refNamespace = reader.getNamespaceURI(refPrefix); if (refNamespace != null && refNamespace.length() > 0) { newPrefix = OMSerializerUtil.generateSetPrefix(refPrefix, refNamespace, writer, true); // If the prefix is not associated with a namespace yet, remember it so that we can // write out a namespace declaration if (newPrefix != null) { if (DEBUG_ENABLED) { log.debug( "An xmlns:" + newPrefix + "=\"" + refNamespace + "\" will be written"); } if (writePrefixList == null) { writePrefixList = new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(refNamespace); } } } } } } } // Now write out the list of namespace declarations in this list that we constructed // while doing the "set" processing. if (writePrefixList != null) { for (int i = 0; i < writePrefixList.size(); i++) { String prefix = (String) writePrefixList.get(i); String namespace = (String) writeNSList.get(i); if (prefix != null) { if (namespace == null) { writer.writeNamespace(prefix, ""); } else { writer.writeNamespace(prefix, namespace); } } else { writer.writeDefaultNamespace(namespace); } } } // Now write the attributes count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { String prefix = reader.getAttributePrefix(i); prefix = (prefix != null && prefix.length() == 0) ? null : prefix; String namespace = reader.getAttributeNamespace(i); namespace = (namespace != null && namespace.length() == 0) ? null : namespace; if (prefix == null && namespace != null) { // Default namespaces are not allowed on an attribute reference. // Earlier in this code, a unique prefix was added for this case...now obtain and use it prefix = writer.getPrefix(namespace); //XMLStreamWriter doesn't allow for getPrefix to know whether you're asking for the prefix //for an attribute or an element. So if the namespace matches the default namespace getPrefix will return //the empty string, as if it were an element, in all cases (even for attributes, and even if //there was a prefix specifically set up for this), which is not the desired behavior. //Since the interface is base java, we can't fix it where we need to (by adding an attr boolean to //XMLStreamWriter.getPrefix), so we hack it in here... if (prefix == null || "".equals(prefix)) { for (int j = 0; j < writePrefixList.size(); j++) { if (namespace.equals((String) writeNSList.get(j))) { prefix = (String) writePrefixList.get(j); } } } } else if (namespace != null && !prefix.equals("xml")) { // Use the writer's prefix if it is different, but if the writers // prefix is empty then do not replace because attributes do not // default to the default namespace like elements do. String writerPrefix = writer.getPrefix(namespace); if (!prefix.equals(writerPrefix) && !"".equals(writerPrefix)) { prefix = writerPrefix; } } if (namespace != null) { // Qualified attribute writer.writeAttribute(prefix, namespace, reader.getAttributeLocalName(i), reader.getAttributeValue(i)); } else { // Unqualified attribute writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i)); } } }
From source file:org.apache.axis2.jaxws.context.listener.ParserInputStreamCustomBuilder.java
private HashMap<String, String> getElementNamespaceDeclarations(XMLStreamReader reader) { HashMap<String, String> nsElementDecls = new HashMap<String, String>(); int count = reader.getNamespaceCount(); for (int i = 0; i < count; i++) { String prefix = reader.getNamespacePrefix(i); String namespace = reader.getNamespaceURI(i); if (namespace != null && namespace.length() > 0) { nsElementDecls.put(prefix == null ? "" : prefix, namespace); }/*from ww w .j a va 2s. c o m*/ } return nsElementDecls; }
From source file:org.apache.axis2.jaxws.message.util.impl.SAAJConverterImpl.java
/** * update the tag data of the SOAPElement * * @param NameCreator nc// ww w . j a va2s . c o m * @param element SOAPElement * @param reader XMLStreamReader whose cursor is at START_ELEMENT */ protected void updateTagData(NameCreator nc, SOAPElement element, XMLStreamReader reader, boolean newElement) throws SOAPException { String prefix = reader.getPrefix(); prefix = (prefix == null) ? "" : prefix; // Make sure the prefix is correct if (prefix.length() > 0 && !element.getPrefix().equals(prefix)) { // Due to a bug in Axiom DOM or in the reader...not sure where yet, // there may be a non-null prefix and no namespace String ns = reader.getNamespaceURI(); if (ns != null && ns.length() != 0) { element.setPrefix(prefix); } } if (!newElement) { // Add the namespace declarations from the reader for the missing namespaces int size = reader.getNamespaceCount(); for (int i = 0; i < size; i++) { String pre = reader.getNamespacePrefix(i); String ns = reader.getNamespaceURI(i); if ((pre != null && pre.length() > 0) && (ns == null || ns.length() == 0)) { if (log.isDebugEnabled()) { log.debug("The prefix is (" + pre + ") but there is no namespace. " + "This erroneous declaration is skipped."); } } else { String existingNS = element.getNamespaceURI(pre); if (!ns.equals(existingNS)) { element.removeNamespaceDeclaration(pre); // Is it necessary to remove the existing prefix/ns element.addNamespaceDeclaration(pre, ns); } } } } else { // Add the namespace declarations from the reader int size = reader.getNamespaceCount(); for (int i = 0; i < size; i++) { String newPrefix = reader.getNamespacePrefix(i); String newNS = reader.getNamespaceURI(i); if ((newPrefix != null && newPrefix.length() > 0) && (newNS == null || newNS.length() == 0)) { // Due to a bug in Axiom DOM or the reader, I have // seen cases where the prefix is non-null but there is not // namespace. Example: prefix is axis2ns3 and namespace is null. // This is an error..log, tolerate and continue if (log.isDebugEnabled()) { log.debug("The prefix is (" + newPrefix + ") but there is no namespace. " + "This erroneous declaration is skipped."); } } else { element.addNamespaceDeclaration(newPrefix, newNS); } } } addAttributes(nc, element, reader); return; }
From source file:org.apache.ode.utils.DOMUtils.java
private static void parse(XMLStreamReader reader, Document doc, Node parent) throws XMLStreamException { int event = reader.getEventType(); while (reader.hasNext()) { switch (event) { case XMLStreamConstants.START_ELEMENT: // create element Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName()); if (reader.getPrefix() != null && reader.getPrefix() != "") { e.setPrefix(reader.getPrefix()); }//from ww w . jav a 2 s . c o m parent.appendChild(e); // copy namespaces for (int ns = 0; ns < reader.getNamespaceCount(); ns++) { String uri = reader.getNamespaceURI(ns); String prefix = reader.getNamespacePrefix(ns); declare(e, uri, prefix); } // copy attributes for (int att = 0; att < reader.getAttributeCount(); att++) { String name = reader.getAttributeLocalName(att); String prefix = reader.getAttributePrefix(att); if (prefix != null && prefix.length() > 0) { name = prefix + ":" + name; } Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name); attr.setValue(reader.getAttributeValue(att)); e.setAttributeNode(attr); } // sub-nodes if (reader.hasNext()) { reader.next(); parse(reader, doc, e); } if (parent instanceof Document) { while (reader.hasNext()) reader.next(); return; } break; case XMLStreamConstants.END_ELEMENT: return; case XMLStreamConstants.CHARACTERS: if (parent != null) { parent.appendChild(doc.createTextNode(reader.getText())); } break; case XMLStreamConstants.COMMENT: if (parent != null) { parent.appendChild(doc.createComment(reader.getText())); } break; case XMLStreamConstants.CDATA: parent.appendChild(doc.createCDATASection(reader.getText())); break; case XMLStreamConstants.PROCESSING_INSTRUCTION: parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData())); break; case XMLStreamConstants.ENTITY_REFERENCE: parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData())); break; case XMLStreamConstants.NAMESPACE: case XMLStreamConstants.ATTRIBUTE: break; default: break; } if (reader.hasNext()) { event = reader.next(); } } }