javax StreamSource 的目的是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18538288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what is the purpose of javax StreamSource
提问by Ted
I am parsing an xml document being read in as an InputStream, and an exampleI'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 descriptionisn't helpful: "Acts as a holder for a transformation Source in the form of a stream of XML markup."
我正在解析作为 InputStream 读入的 xml 文档,并且我看到的一个示例首先将流置于 javax.xml.transform.stream.StreamSource 中。当我可以解析读入的流时,为什么要这样做?Java API 的描述没有帮助:“作为 XML 标记流形式的转换源的持有者。”
Example with StreamSource:
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:
没有 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();
采纳答案by Henry
It is an abstraction so that the same parsing code can be used for a variety of sources (note: StreamSource
implements Source
):
它是一种抽象,因此相同的解析代码可用于各种来源(注意: StreamSource
实现Source
):
- XMLInputFactory.createXMLStreamReader(Source)
- Validator.validate(Source)
- Transformer.transfrom(Source, Result)
- Unmarshaller.unmarshal(Source, Class)
- XMLInputFactory.createXMLStreamReader(Source)
- Validator.validate(来源)
- Transformer.transfrom(来源,结果)
- Unmarshaller.unmarshal(来源,类)
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
).
从文件中获取 XML 只是一种可能性。还有Source
for DOM( DOMSource
)、SAX( SAXSource
)、StAX( StAXSource
) 和 JAXB( JAXBSource
) 的实现。