java类javax.xml.stream.XMLStreamConstants的实例源码

XmlUtil.java 文件源码 项目:powsybl-core 阅读 25 收藏 0 点赞 0 评论 0
public static String readUntilEndElement(String endElementName, XMLStreamReader reader, XmlEventHandler eventHandler) throws XMLStreamException {
    String text = null;
    int event;
    while (!((event = reader.next()) == XMLStreamConstants.END_ELEMENT
            && reader.getLocalName().equals(endElementName))) {
        text = null;
        switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (eventHandler != null) {
                    eventHandler.onStartElement();
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                text = reader.getText();
                break;

            default:
                break;
        }
    }
    return text;
}
DocumentStaxUtils.java 文件源码 项目:gate-core 阅读 24 收藏 0 点赞 0 评论 0
/**
 * Processes a GateDocumentFeatures or Annotation element to build a
 * feature map. The element is expected to contain Feature children,
 * each with a Name and Value. The reader will be returned positioned
 * on the closing GateDocumentFeatures or Annotation tag.
 * 
 * @throws XMLStreamException
 */
public static FeatureMap readFeatureMap(XMLStreamReader xsr)
        throws XMLStreamException {
  FeatureMap fm = Factory.newFeatureMap();
  while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
    xsr.require(XMLStreamConstants.START_ELEMENT, null, "Feature");
    Object featureName = null;
    Object featureValue = null;
    while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
      if("Name".equals(xsr.getLocalName())) {
        featureName = readFeatureNameOrValue(xsr);
      }
      else if("Value".equals(xsr.getLocalName())) {
        featureValue = readFeatureNameOrValue(xsr);
      }
      else {
        throw new XMLStreamException("Feature element should contain "
                + "only Name and Value children", xsr.getLocation());
      }
    }
    fm.put(featureName, featureValue);
  }
  return fm;
}
Bug6481678.java 文件源码 项目:openjdk-jdk10 阅读 26 收藏 0 点赞 0 评论 0
@Test
public void testRootElementNamespace() {
    is = new java.io.ByteArrayInputStream(getXML().getBytes());
    try {
        XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter);

        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefixApple) && sr.getNamespaceURI(0).equals(namespaceURIApple));
                }
            }
        }
    } catch (Exception ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
XMLSpectrumHeaderBuilder.java 文件源码 项目:dp-mzml 阅读 19 收藏 0 点赞 0 评论 0
@Override
public void accept(XMLStreamReader xr) {
    if((xr.getEventType() == XMLStreamConstants.START_ELEMENT) 
            && xr.getLocalName().equals("cvParam")) {

        if (xr.getAttributeValue(null, "accession").equals("MS:1000511")) {
            this.currHeader.setMsLevel(Integer.valueOf(xr.getAttributeValue(null, "value")));
        } else if(xr.getAttributeValue(null, "accession").equals("MS:1000016")) {
            // normalize to seconds if unit is a minute
            double norm = xr.getAttributeValue(null, "unitAccession")
                    .equals("UO:0000031") 
                ? 60.0 
                : 1.0;
            this.currHeader.setScanStartTime(norm * Double.valueOf(xr.getAttributeValue(null, "value")));
        } else if(xr.getAttributeValue(null, "accession").equals("MS:1000744")) {
            this.currHeader.setSelectedIonMz(Double.valueOf(xr.getAttributeValue(null, "value")));
        } else if(xr.getAttributeValue(null, "accession").equals("MS:1000041")) {
            this.currHeader.setSelectedIonCharge(Integer.valueOf(xr.getAttributeValue(null, "value")));
        } else if(xr.getAttributeValue(null, "accession").equals("MS:1000042")) {
            this.currHeader.setSelectedIonIntensity(Double.valueOf(xr.getAttributeValue(null, "value")));
        }
    }
}
StaxReader.java 文件源码 项目:lams 阅读 18 收藏 0 点赞 0 评论 0
@Override
protected int pullNextEvent() {
    try {
        switch (in.next()) {
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.START_ELEMENT:
            return START_NODE;
        case XMLStreamConstants.END_DOCUMENT:
        case XMLStreamConstants.END_ELEMENT:
            return END_NODE;
        case XMLStreamConstants.CHARACTERS:
            return TEXT;
        case XMLStreamConstants.COMMENT:
            return COMMENT;
        default:
            return OTHER;
        }
    } catch (final XMLStreamException e) {
        throw new StreamException(e);
    }
}
MappingReader.java 文件源码 项目:lams 阅读 18 收藏 0 点赞 0 评论 0
private Document toDom4jDocument(XMLEventReader staxEventReader, Origin origin) {
    STAXEventReader dom4jStaxEventReader = new STAXEventReader();
    try {
        // the dom4j converter class is touchy about comments (aka, comments make it implode)
        // so wrap the event stream in a filtering stream to filter out comment events
        staxEventReader = new FilteringXMLEventReader( staxEventReader ) {
            @Override
            protected XMLEvent filterEvent(XMLEvent event, boolean peek) {
                return event.getEventType() == XMLStreamConstants.COMMENT
                        ? null
                        : event;
            }
        };

        return dom4jStaxEventReader.readDocument( staxEventReader );
    }
    catch (XMLStreamException e) {
        throw new InvalidMappingException( "Unable to read StAX source as dom4j Document for processing", origin, e );
    }
}
FreeColXMLReader.java 文件源码 项目:freecol 阅读 29 收藏 0 点赞 0 评论 0
/**
 * {@inheritDoc}
 */
@Override
public int nextTag() throws XMLStreamException {
    int tag = super.nextTag();
    if (tracing) {
        switch (tag) {
        case XMLStreamConstants.START_ELEMENT:
            System.err.println("[" + getLocalName());
            break;
        case XMLStreamConstants.END_ELEMENT:
            System.err.println(getLocalName() + "]");
            break;
        default:
            System.err.println((tagStrings.containsKey(tag))
                ? tagStrings.get(tag)
                : "Weird tag: " + tag);
            break;
        }
    }
    return tag;
}
ProcessingInstructionTest.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
@Test
public void testPITargetAndData() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        String PITarget = "soffice";
        String PIData = "WebservicesArchitecture";
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<?" + PITarget + " " + PIData + "?>" + "<foo></foo>";
        // System.out.println("XML = " + xml) ;
        InputStream is = new java.io.ByteArrayInputStream(xml.getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION) {
                String target = sr.getPITarget();
                String data = sr.getPIData();
                Assert.assertTrue(target.equals(PITarget) && data.equals(PIData));
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
DeploymentDescriptorParser.java 文件源码 项目:OpenJSharp 阅读 24 收藏 0 点赞 0 评论 0
/**
 * Parses the handler and role information and sets it
 * on the {@link WSBinding}.
 *
 * @return true if <handler-chains> element present in DD
 *         false otherwise.
 */
protected boolean setHandlersAndRoles(WSBinding binding, XMLStreamReader reader, QName serviceName, QName portName) {

    if (reader.getEventType() == XMLStreamConstants.END_ELEMENT ||
            !reader.getName().equals(HandlerChainsModel.QNAME_HANDLER_CHAINS)) {
        return false;
    }

    HandlerAnnotationInfo handlerInfo = HandlerChainsModel.parseHandlerFile(
            reader, classLoader, serviceName, portName, binding);

    binding.setHandlerChain(handlerInfo.getHandlers());
    if (binding instanceof SOAPBinding) {
        ((SOAPBinding) binding).setRoles(handlerInfo.getRoles());
    }

    // move past </handler-chains>
    XMLStreamReaderUtil.nextContent(reader);
    return true;
}
NamespaceTest.java 文件源码 项目:openjdk-jdk10 阅读 23 收藏 0 点赞 0 评论 0
@Test
public void testNamespaceContext() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(childElement)) {
                    NamespaceContext context = sr.getNamespaceContext();
                    Assert.assertTrue(context.getPrefix(namespaceURI).equals(prefix));
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
StreamReaderTest.java 文件源码 项目:openjdk-jdk10 阅读 16 收藏 0 点赞 0 评论 0
/**
 * CR 6631264 / sjsxp Issue 45:
 * https://sjsxp.dev.java.net/issues/show_bug.cgi?id=45
 * XMLStreamReader.hasName() should return false for ENTITY_REFERENCE
 */
@Test
public void testHasNameOnEntityEvent() throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    XMLStreamReader r = xif.createXMLStreamReader(
            this.getClass().getResourceAsStream("ExternalDTD.xml"));
    while (r.next() != XMLStreamConstants.ENTITY_REFERENCE) {
        System.out.println("event type: " + r.getEventType());
        continue;
    }
    if (r.hasName()) {
        System.out.println("hasName returned true on ENTITY_REFERENCE event.");
    }
    Assert.assertFalse(r.hasName()); // fails
}
StAXSource.java 文件源码 项目:OpenJSharp 阅读 20 收藏 0 点赞 0 评论 0
/**
 * Creates a new {@link javax.xml.transform.Source} for the given
 * {@link XMLStreamReader}.
 *
 * The XMLStreamReader must be pointing at either a
 * {@link javax.xml.stream.XMLStreamConstants#START_DOCUMENT} or
 * {@link javax.xml.stream.XMLStreamConstants#START_ELEMENT} event.
 *
 * @param reader XMLStreamReader that will be exposed as a Source
 * @param eagerQuit if true, when the conversion is completed, leave the cursor to the last
 *                  event that was fired (such as end element)
 * @param inscope inscope Namespaces
 *                array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }
 * @throws IllegalArgumentException iff the reader is null
 * @throws IllegalStateException iff the reader is not pointing at either a
 * START_DOCUMENT or START_ELEMENT event
 */
public StAXSource(XMLStreamReader reader, boolean eagerQuit, @NotNull String[] inscope) {
    if( reader == null )
        throw new IllegalArgumentException();
    this.staxReader = reader;

    int eventType = reader.getEventType();
    if (!(eventType == XMLStreamConstants.START_DOCUMENT)
        && !(eventType == XMLStreamConstants.START_ELEMENT)) {
        throw new IllegalStateException();
    }

    this.reader = new XMLStreamReaderToContentHandler(reader,repeater,eagerQuit,false,inscope);

    super.setXMLReader(pseudoParser);
    // pass a dummy InputSource. We don't care
    super.setInputSource(new InputSource());
}
Bug6481678.java 文件源码 项目:openjdk-jdk10 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void testReadingNamespace() {
    is = new java.io.ByteArrayInputStream(getXML().getBytes());
    try {
        XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter);

        while (sr.hasNext()) {
            int eventType = sr.getEventType();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefixApple) && sr.getNamespaceURI(0).equals(namespaceURIApple));
                }
            }
            eventType = sr.next();
        }
    } catch (Exception ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
XMLStreamReaderImpl.java 文件源码 项目:OpenJSharp 阅读 23 收藏 0 点赞 0 评论 0
protected List getNotationDecls(){
    if(fEventType == XMLStreamConstants.DTD){
        if(fScanner.fDTDScanner == null) return null;
        DTDGrammar grammar = ((XMLDTDScannerImpl)(fScanner.fDTDScanner)).getGrammar();
        if(grammar == null) return null;
        List notations = grammar.getNotationDecls();

        Iterator it = notations.iterator();
        ArrayList list = new ArrayList();
        while(it.hasNext()){
            XMLNotationDecl ni = (XMLNotationDecl)it.next();
            if(ni!= null){
                list.add(new NotationDeclarationImpl(ni));
            }
        }
        return list;
    }
    return null;
}
StAXSourceTest.java 文件源码 项目:openjdk-jdk10 阅读 25 收藏 0 点赞 0 评论 0
/**
 * @bug 8152530
 * Verifies that StAXSource handles empty namespace properly. NPE was thrown
 * before the fix.
 * @throws Exception if the test fails
 */
@Test
public final void testStAXSourceWEmptyNS() throws Exception {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<EntityList>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "  <Entity xmlns=\"\">\n"
        + "  </Entity>\n"
        + "</EntityList> ";

    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
    xsr.nextTag();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("Entity")) {
        StringWriter stringResult = new StringWriter();
        t.transform(new StAXSource(xsr), new StreamResult(stringResult));
        System.out.println("result: \n" + stringResult.toString());
    }
}
StaxUnmarshallerContext.java 文件源码 项目:aws-sdk-java-v2 阅读 19 收藏 0 点赞 0 评论 0
/**
 * Returns the text contents of the current element being parsed.
 *
 * @return The text contents of the current element being parsed.
 */
public String readText() throws XMLStreamException {
    if (isInsideResponseHeader()) {
        return getHeader(currentHeader);
    }
    if (currentEvent.isAttribute()) {
        Attribute attribute = (Attribute) currentEvent;
        return attribute.getValue();
    }

    StringBuilder sb = new StringBuilder();
    while (true) {
        XMLEvent event = eventReader.peek();
        if (event.getEventType() == XMLStreamConstants.CHARACTERS) {
            eventReader.nextEvent();
            sb.append(event.asCharacters().getData());
        } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
            return sb.toString();
        } else {
            throw new RuntimeException("Encountered unexpected event: " + event.toString());
        }
    }
}
Bug6489502.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
@Test
public void testEventReader2() {
    try {
        // Now advance underlying reader and then call peek on event reader
        XMLStreamReader s1 = inputFactory.createXMLStreamReader(new java.io.StringReader(xml));
        Assert.assertEquals(s1.getEventType(), XMLStreamConstants.START_DOCUMENT);
        s1.next();
        s1.next(); // advance to <TITLE>
        Assert.assertTrue(s1.getLocalName().equals("TITLE"));

        XMLEventReader e3 = inputFactory.createXMLEventReader(s1);
        Assert.assertEquals(e3.peek().getEventType(), XMLStreamConstants.START_ELEMENT);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
Bug6481678.java 文件源码 项目:openjdk-jdk10 阅读 21 收藏 0 点赞 0 评论 0
@Test
public void testChildElementNamespace() {
    is = new java.io.ByteArrayInputStream(getXML().getBytes());
    try {
        XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(childElement)) {
                    QName qname = sr.getName();
                    Assert.assertTrue(qname.getPrefix().equals(prefixApple) && qname.getNamespaceURI().equals(namespaceURIApple)
                            && qname.getLocalPart().equals(childElement));
                }
            }
        }
    } catch (Exception ex) {
        Assert.fail("Exception: " + ex.getMessage());
    }
}
NamespaceTest.java 文件源码 项目:openjdk-jdk10 阅读 30 收藏 0 点赞 0 评论 0
@Test
public void testNamespaceCount() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    int count = sr.getNamespaceCount();
                    Assert.assertTrue(count == 1);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
DeploymentDescriptorParser.java 文件源码 项目:openjdk-jdk10 阅读 27 收藏 0 点赞 0 评论 0
/**
 * Parses the handler and role information and sets it
 * on the {@link WSBinding}.
 *
 * @return true if <handler-chains> element present in DD
 *         false otherwise.
 */
protected boolean setHandlersAndRoles(WSBinding binding, XMLStreamReader reader, QName serviceName, QName portName) {

    if (reader.getEventType() == XMLStreamConstants.END_ELEMENT ||
            !reader.getName().equals(HandlerChainsModel.QNAME_HANDLER_CHAINS)) {
        return false;
    }

    HandlerAnnotationInfo handlerInfo = HandlerChainsModel.parseHandlerFile(
            reader, classLoader, serviceName, portName, binding);

    binding.setHandlerChain(handlerInfo.getHandlers());
    if (binding instanceof SOAPBinding) {
        ((SOAPBinding) binding).setRoles(handlerInfo.getRoles());
    }

    // move past </handler-chains>
    XMLStreamReaderUtil.nextContent(reader);
    return true;
}
StAXSource.java 文件源码 项目:openjdk-jdk10 阅读 27 收藏 0 点赞 0 评论 0
/**
 * Creates a new {@link javax.xml.transform.Source} for the given
 * {@link XMLStreamReader}.
 *
 * The XMLStreamReader must be pointing at either a
 * {@link javax.xml.stream.XMLStreamConstants#START_DOCUMENT} or
 * {@link javax.xml.stream.XMLStreamConstants#START_ELEMENT} event.
 *
 * @param reader XMLStreamReader that will be exposed as a Source
 * @param eagerQuit if true, when the conversion is completed, leave the cursor to the last
 *                  event that was fired (such as end element)
 * @param inscope inscope Namespaces
 *                array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }
 * @throws IllegalArgumentException iff the reader is null
 * @throws IllegalStateException iff the reader is not pointing at either a
 * START_DOCUMENT or START_ELEMENT event
 */
public StAXSource(XMLStreamReader reader, boolean eagerQuit, @NotNull String[] inscope) {
    if( reader == null )
        throw new IllegalArgumentException();
    this.staxReader = reader;

    int eventType = reader.getEventType();
    if (!(eventType == XMLStreamConstants.START_DOCUMENT)
        && !(eventType == XMLStreamConstants.START_ELEMENT)) {
        throw new IllegalStateException();
    }

    this.reader = new XMLStreamReaderToContentHandler(reader,repeater,eagerQuit,false,inscope);

    super.setXMLReader(pseudoParser);
    // pass a dummy InputSource. We don't care
    super.setInputSource(new InputSource());
}
DefaultAttributeTest.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
@Test
public void testStreamReader() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();
    XMLOutputFactory ofac = XMLOutputFactory.newInstance();

    try {
        ifac.setProperty(ifac.IS_REPLACING_ENTITY_REFERENCES, new Boolean(false));

        XMLStreamReader re = ifac.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE));

        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT && re.getLocalName().equals("bookurn")) {
                Assert.assertTrue(re.getAttributeCount() == 0, "No attributes are expected for <bookurn> ");
                Assert.assertTrue(re.getNamespaceCount() == 2, "Two namespaces are expected for <bookurn> ");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
StreamReaderTest.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
/**
 * Verifies that after switching to a different XML Version (1.1), the parser
 * is initialized properly (the listener was not registered in this case).
 *
 * @param path the path to XML source
 * @throws Exception
 */
@Test(dataProvider = "getPaths")
public void testSwitchXMLVersions(String path) throws Exception {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true);
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(
            this.getClass().getResourceAsStream(path));

    while (xmlStreamReader.hasNext()) {
        int event = xmlStreamReader.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (xmlStreamReader.getLocalName().equals("body")) {
                String elementText = xmlStreamReader.getElementText();
                Assert.assertTrue(!elementText.contains("</body>"),
                        "Fail: elementText contains </body>");
            }
        }
    }
}
Jsr173MR1Req8Test.java 文件源码 项目:openjdk-jdk10 阅读 24 收藏 0 点赞 0 评论 0
@Test
public void testDefaultAttrNS() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();

    try {
        XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE1));
        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                // System.out.println("#attrs = " + re.getAttributeCount());
                Assert.assertTrue(re.getAttributeCount() == 2);
                // This works if "" is replaced by null too
                // System.out.println("attr1 = " + re.getAttributeValue("",
                // "attr1"));
                Assert.assertTrue(re.getAttributeValue("", "attr1").equals("pass"));
            }
        }
        re.close();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
Jsr173MR1Req5Test.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testAttributeCountNS() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();

    try {
        // Turn on NS awareness to not count xmlns as attributes
        ifac.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE);

        XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE1));
        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                // System.out.println("#attrs = " + re.getAttributeCount());
                Assert.assertTrue(re.getAttributeCount() == 1);
            }
        }
        re.close();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
FreeColXMLReader.java 文件源码 项目:FreeCol 阅读 23 收藏 0 点赞 0 评论 0
/**
 * {@inheritDoc}
 */
@Override
public int nextTag() throws XMLStreamException {
    int tag = super.nextTag();
    if (tracing) {
        switch (tag) {
        case XMLStreamConstants.START_ELEMENT:
            System.err.println("[" + getLocalName());
            break;
        case XMLStreamConstants.END_ELEMENT:
            System.err.println(getLocalName() + "]");
            break;
        default:
            System.err.println((tagStrings.containsKey(tag))
                ? tagStrings.get(tag)
                : "Weird tag: " + tag);
            break;
        }
    }
    return tag;
}
XMLStreamReaderImpl.java 文件源码 项目:openjdk-jdk10 阅读 24 收藏 0 点赞 0 评论 0
protected List<NotationDeclaration> getNotationDecls() {
    if (fEventType == XMLStreamConstants.DTD) {
        if (fScanner.fDTDScanner == null) {
            return null;
        }
        DTDGrammar grammar = ((XMLDTDScannerImpl) (fScanner.fDTDScanner)).getGrammar();
        if (grammar == null) {
            return null;
        }
        List<XMLNotationDecl> notations = grammar.getNotationDecls();
        ArrayList<NotationDeclaration> list = new ArrayList<>();
        for (XMLNotationDecl notation : notations) {
            if (notation != null) {
                list.add(new NotationDeclarationImpl(notation));
            }
        }
        return list;
    }
    return null;
}
CDataChunkSizeTest.java 文件源码 项目:openjdk-jdk10 阅读 16 收藏 0 点赞 0 评论 0
@Test(dataProvider = "xml-data")
public void testStAX(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception {
    XMLInputFactory xifactory = XMLInputFactory.newInstance();
    xifactory.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true);
    if (chunkSize > 0) {
        xifactory.setProperty(CDATA_CHUNK_SIZE, chunkSize);
    }
    XMLStreamReader streamReader = xifactory.createXMLStreamReader(new StringReader(xml));

    StringBuilder cdata = new StringBuilder();
    int numOfChunks = 0;
    boolean isWithinLimit = true;
    while (streamReader.hasNext()) {
        int eventType = streamReader.next();
        switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                debugPrint("\nElement: " + streamReader.getLocalName());
                break;
            case XMLStreamConstants.CDATA:
                String text = streamReader.getText();
                numOfChunks++;
                if (text.length() > chunkSize) {
                    isWithinLimit = false;
                }
                debugPrint("\nCDATA: " + text.length());
                cdata.append(text);
                break;
            case XMLStreamConstants.CHARACTERS:
                debugPrint("\nCharacters: " + streamReader.getText().length());
                break;
        }
    }
    debugPrint("CData in single chunk:" + cdata.toString().length());
    Assert.assertEquals(numOfChunks, expectedNumOfChunks);
    Assert.assertEquals(isWithinLimit, withinLimit);
}
StAXParser.java 文件源码 项目:pzubaha 阅读 17 收藏 0 点赞 0 评论 0
/**
 * Method for parsing orders XML.
 * @param is input stream for parsing.
 * @return SortedMap of OrderBook's mapping key name.
 * @throws FileNotFoundException if there is no such file.
 * @throws XMLStreamException The base exception for unexpected processing errors.  This Exception
 * class is used to report well-formedness errors as well as unexpected
 * processing conditions.
 */
public SortedMap<String, OrderBook> parse(InputStream is) throws FileNotFoundException, XMLStreamException {
    SortedMap<String, OrderBook> orders = new TreeMap<>(String::compareTo);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = factory.createXMLStreamReader(is);
    OrderBook orderBook;
    String book;
    reader.next();
    while (reader.hasNext()) {
        if (reader.next() == XMLStreamConstants.START_ELEMENT) {
            if (reader.isStartElement()) {
                book = reader.getAttributeValue(null, "book");
                if ("AddOrder".equals(reader.getLocalName())) {
                    if (!orders.containsKey(book)) {
                        orderBook = new OrderBook(book);
                        orders.put(book, orderBook);
                    } else {
                        orderBook = orders.get(book);
                    }
                    orderBook.addOrder(OrderBook.OPERATION.valueOf(reader.getAttributeValue(null, "operation")),
                            Integer.parseInt(reader.getAttributeValue(null, "orderId")),
                            Integer.parseInt(reader.getAttributeValue(null, "volume")),
                            Float.parseFloat(reader.getAttributeValue(null, "price")));
                } else {
                    orders.get(book).delOrder(Integer.parseInt(reader.getAttributeValue(null, "orderId")));
                }
            }
        }
    }
    return orders;
}
XMLStreamConstantsUtils.java 文件源码 项目:lams 阅读 19 收藏 0 点赞 0 评论 0
/**
 * Get the human readable event name for the numeric event id
 */
public static String getEventName(int eventId) {
    switch (eventId) {
        case XMLStreamConstants.START_ELEMENT:
            return "StartElementEvent";
        case XMLStreamConstants.END_ELEMENT:
            return "EndElementEvent";
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            return "ProcessingInstructionEvent";
        case XMLStreamConstants.CHARACTERS:
            return "CharacterEvent";
        case XMLStreamConstants.COMMENT:
            return "CommentEvent";
        case XMLStreamConstants.START_DOCUMENT:
            return "StartDocumentEvent";
        case XMLStreamConstants.END_DOCUMENT:
            return "EndDocumentEvent";
        case XMLStreamConstants.ENTITY_REFERENCE:
            return "EntityReferenceEvent";
        case XMLStreamConstants.ATTRIBUTE:
            return "AttributeBase";
        case XMLStreamConstants.DTD:
            return "DTDEvent";
        case XMLStreamConstants.CDATA:
            return "CDATA";
    }
    return "UNKNOWN_EVENT_TYPE";
}


问题


面经


文章

微信
公众号

扫码关注公众号