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();
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.
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.
It is an abstraction so that the same parsing code can be used for a variety of sources (note: StreamSource
implements Source
):
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With