本文整理汇总了Java中javax.xml.parsers.DocumentBuilderFactory类的典型用法代码示例。如果您正苦于以下问题:Java DocumentBuilderFactory类的具体用法?Java DocumentBuilderFactory怎么用?Java DocumentBuilderFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DocumentBuilderFactory类属于javax.xml.parsers包,在下文中一共展示了DocumentBuilderFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: InstanceCreator
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
public InstanceCreator(InputStream in) {
try {
this.relations = new HashMap<Relation,Set<List<String>>>();
this.atoms = new LinkedHashSet<String>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
this.document = builder.parse(in);
} catch (SAXException sxe) {
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
throw new InstanceCreationException("Error generated during parsing: " + x.getMessage());
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
throw new InstanceCreationException("Parser with specified options cannot be built: " + pce.getMessage());
} catch (IOException ioe) {
// I/O error
throw new InstanceCreationException("I/O error: " + ioe.getMessage());
} finally {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
示例2: setFeature
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
private void setFeature(DocumentBuilderFactory factory, String feature, boolean enable)
{
try
{
if (ADDITIONAL_FEATURE_X_INCLUDE_AWARE.equals(feature))
{
factory.setXIncludeAware(enable);
}
else if (ADDITIONAL_FEATURE_EXPAND_ENTITY_REFERENCES.equals(feature))
{
factory.setExpandEntityReferences(enable);
}
else
{
factory.setFeature(feature, enable);
}
debug(debugCounter+" DocumentBuilderFactory "+feature+" "+enable);
}
catch (ParserConfigurationException pce)
{
logConfigurationFailure(factory.getClass().getName(), feature, pce);
}
}
示例3: testJobAttemptsXML
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
@Test
public void testJobAttemptsXML() throws Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1")
.path("mapreduce").path("jobs").path(jobId).path("jobattempts")
.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList attempts = dom.getElementsByTagName("jobAttempts");
assertEquals("incorrect number of elements", 1, attempts.getLength());
NodeList info = dom.getElementsByTagName("jobAttempt");
verifyJobAttemptsXML(info, jobsMap.get(id));
}
}
示例4: getMaxRId
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("Relationships/*");
NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
int idNum = Integer.parseInt(id.substring("rId".length()));
this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
}
return this.maxRId;
}
示例5: toDom
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
private static org.w3c.dom.Document toDom(final Document doc) {
try {
final XMLOutputter xmlOutputter = new XMLOutputter();
final StringWriter elemStrWriter = new StringWriter();
xmlOutputter.output(doc, elemStrWriter);
final byte[] xmlBytes = elemStrWriter.toString().getBytes();
final DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
dbf.setNamespaceAware(true);
return dbf.newDocumentBuilder().parse(
new ByteArrayInputStream(xmlBytes));
} catch (final Exception e) {
return null;
}
}
示例6: test1
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
@Test
public void test1() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml"));
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema s = sf.newSchema(Bug5072946.class.getResource("Bug5072946.xsd"));
Validator v = s.newValidator();
DOMResult r = new DOMResult();
// r.setNode(dbf.newDocumentBuilder().newDocument());
v.validate(new DOMSource(dom), r);
Node node = r.getNode();
Assert.assertNotNull(node);
Node fc = node.getFirstChild();
Assert.assertTrue(fc instanceof Element);
Element e = (Element) fc;
Assert.assertEquals("value", e.getAttribute("foo"));
}
示例7: load
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
public boolean load(InputStream s)
{
try
{
Source file = new StreamSource(s) ;
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ;
Result res = new DOMResult(doc) ;
TransformerFactory tr = TransformerFactory.newInstance();
Transformer xformer = tr.newTransformer();
xformer.transform(file, res);
m_doc = doc;
m_elem = m_doc.getDocumentElement();
return true;
}
catch (Exception e)
{
LogTagError.log(e);
return false;
}
}
示例8: buildDOMderivation
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
public static Document buildDOMderivation(ArrayList<ParseTreeCollection> all, String sentence) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder constructor = factory.newDocumentBuilder();
derivDoc = constructor.newDocument();
derivDoc.setXmlVersion("1.0");
derivDoc.setXmlStandalone(false);
Element root = derivDoc.createElement("parses");
root.setAttribute("sentence", sentence);
for (ParseTreeCollection ptc : all)
{
buildOne(root, ptc.getDerivationTree().getDomNodes().get(0), ptc.getDerivedTree().getDomNodes().get(0), ptc.getSemantics(), ptc.getSpecifiedSemantics());
}
// finally we do not forget the root
derivDoc.appendChild(root);
return derivDoc;
} catch (ParserConfigurationException e) {
System.err.println(e);
return null;
}
}
示例9: ScriptDocument
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
public ScriptDocument(String name, InputStream input)
{
_name = name;
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
final DocumentBuilder builder = factory.newDocumentBuilder();
_document = builder.parse(input);
}
catch (SAXException sxe)
{
// Error generated during parsing)
Exception x = sxe;
if (sxe.getException() != null)
{
x = sxe.getException();
}
_log.warning(getClass().getSimpleName() + ": " + x.getMessage());
}
catch (ParserConfigurationException pce)
{
// Parser with specified options can't be built
_log.log(Level.WARNING, "", pce);
}
catch (IOException ioe)
{
// I/O error
_log.log(Level.WARNING, "", ioe);
}
}
示例10: readLogEntry
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
/**
* Constructs an instance of StoreLogEntry using parts of a row from ResultSet. Used for creating the store operation for Undo.
*
* @param reader
* ResultSet whose row has operation information.
* @param offset
* Reader offset for column that begins operation information.
*/
public static StoreLogEntry readLogEntry(ResultSet reader,
int offset) throws SQLException {
try {
UUID shardIdRemoves = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 4)) ? null : UUID.fromString(reader.getString(offset + 4));
UUID shardIdAdds = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 5)) ? null : UUID.fromString(reader.getString(offset + 5));
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(reader.getSQLXML(offset + 2).getBinaryStream());
return new StoreLogEntry(UUID.fromString(reader.getString(offset)), StoreOperationCode.forValue(reader.getInt(offset + 1)),
(Element) doc.getFirstChild(), StoreOperationState.forValue(reader.getInt(offset + 3)), shardIdRemoves, shardIdAdds);
}
catch (SAXException | IOException | ParserConfigurationException e) {
e.printStackTrace();
return null;
}
}
示例11: load
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
public static void load() {
File dir = NavyCraft.instance.getDataFolder();
if (!dir.exists())
dir.mkdir();
File config = new File(NavyCraft.instance.getDataFolder(), NavyCraft.instance.configFile.filename);
if (!config.exists()) {
return;
}
Document doc = null;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(config.toURI().getPath());
doc.getDocumentElement().normalize();
NodeList list;
for(Object configLine : NavyCraft.instance.configFile.ConfigSettings.keySet().toArray()) {
String configKey = (String) configLine;
list = doc.getElementsByTagName(configKey);
try {
String value = list.item(0).getChildNodes().item(0).getNodeValue();
NavyCraft.instance.configFile.ConfigSettings.put(configKey, value);
} catch (Exception ex){
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
示例12: generateForecast
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
private void generateForecast(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException {
city = c;
// creating the URL
String url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + city + ",us&mode=xml&cnt=6&appid=" + APIKey;
// printing out XML
URL urlString = new URL(url);
URLConnection conn = urlString.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
TransformerFactory transformer = TransformerFactory.newInstance();
Transformer xform = transformer.newTransformer();
xform.transform(new DOMSource(doc), new StreamResult(System.out));
}
示例13: getDocument
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
private static Document getDocument(InputStream in) {
Document document = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(in);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
return document;
}
示例14: writeTo
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
public void writeTo(SOAPMessage saaj) throws SOAPException {
try {
// TODO what about in-scope namespaces
// Not very efficient consider implementing a stream buffer
// processor that produces a DOM node from the buffer.
Transformer t = XmlUtil.newTransformer();
SOAPHeader header = saaj.getSOAPHeader();
if (header == null)
header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
// t.transform(epr.asSource(localName), new DOMResult(header));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
epr.writeTo(localName, w);
w.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
fac.setNamespaceAware(true);
Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
header.appendChild(eprNodeToAdd);
} catch (Exception e) {
throw new SOAPException(e);
}
}
示例15: testGetTypeInfo
import javax.xml.parsers.DocumentBuilderFactory; //导入依赖的package包/类
/**
* Check usage of TypeInfo interface introduced in DOM L3.
*
* @throws Exception If any errors occur.
*/
@Test
public void testGetTypeInfo() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(new MyErrorHandler());
Document document = docBuilder.parse(xmlFile);
Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
TypeInfo typeInfo = userId.getSchemaTypeInfo();
assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));
Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
TypeInfo roletypeInfo = role.getSchemaTypeInfo();
assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
}