Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of javax StreamSource

Tags:

java

xml

I am parsing an xml document being read in as an InputStream, and an example I've seen first stages the stream in a javax.xml.transform.stream.StreamSource. Why do this when I can parse the stream as it's read in? The Java API's description isn't helpful: "Acts as a holder for a transformation Source in the form of a stream of XML markup."

Example with StreamSource:

    XMLInputFactory xif = XMLInputFactory.newFactory();
    StreamSource reportStream = 
              new StreamSource(new URL("file:///myXmlDocURL.xml").openStream());
    XMLStreamReader xmlReader = xif.createXMLStreamReader(reportStream);
    xmlReader.nextTag();
    while (xmlReader.hasNext()) {
        if (xmlReader.getLocalName().equals("attributeICareAbout")) {
            String tempTagValue = xmlReader.getText();
            xmlReader.nextTag();
        }
    }
    xmlReader.close();

Example without StreamSource:

    XMLInputFactory xif = XMLInputFactory.newFactory();        
    XMLStreamReader xmlReader = 
      xif.createXMLStreamReader(new URL("file:///myXmlDocURL.xml").openStream());
    xmlReader.nextTag();
    while (xmlReader.hasNext()) {
        if (xmlReader.getLocalName().equals("attributeIcareAbout")) {
            String tempTagValue = xmlReader.getText();
            xmlReader.nextTag();
        }
    }
    xmlReader.close();
like image 556
Ted Avatar asked Aug 30 '13 17:08

Ted


People also ask

Do we need to close StreamSource in Java?

Streams have a BaseStream. close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files. lines(Path, Charset)) will require closing.

What is stream source?

Stream Source creates Indigenous and women-owned recruitment and contractor management ventures that reinvest in local Nations. We equip Indigenous people with jobs, opportunities and facilitate training in diverse sectors of the economy.


1 Answers

It is an abstraction so that the same parsing code can be used for a variety of sources (note: StreamSource implements Source):

  • XMLInputFactory.createXMLStreamReader(Source)
  • Validator.validate(Source)
  • Transformer.transfrom(Source, Result)
  • Unmarshaller.unmarshal(Source, Class)

Getting XML from a file is just one possibility. There are also implementations of Source for DOM (DOMSource), SAX (SAXSource), StAX (StAXSource), and JAXB (JAXBSource).

like image 115
Henry Avatar answered Sep 22 '22 06:09

Henry