本文整理汇总了Java中javax.xml.parsers.DocumentBuilderFactory.newDocumentBuilder方法的典型用法代码示例。如果您正苦于以下问题:Java DocumentBuilderFactory.newDocumentBuilder方法的具体用法?Java DocumentBuilderFactory.newDocumentBuilder怎么用?Java DocumentBuilderFactory.newDocumentBuilder使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.xml.parsers.DocumentBuilderFactory
的用法示例。
在下文中一共展示了DocumentBuilderFactory.newDocumentBuilder方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: load
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
private static Document load(InputStream in) throws IOException {
Document document = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(in);
} catch (ParserConfigurationException parserConfigurationException) {
parserConfigurationException.printStackTrace();
Assert.fail(parserConfigurationException.toString());
} catch (SAXException saxException) {
saxException.printStackTrace();
Assert.fail(saxException.toString());
}
return document;
}
示例2: testJobIdXML
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
@Test
public void testJobIdXML() 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("history")
.path("mapreduce").path("jobs").path(jobId)
.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 job = dom.getElementsByTagName("job");
verifyHsJobXML(job, appContext);
}
}
示例3: 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;
}
示例4: createParser
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
/** Returns an XML Parser.
* @return an XML Parser.
* @throws ParserConfigurationException if any error occurs
*/
protected DocumentBuilder createParser() throws ParserConfigurationException {
// Create a factory object for creating DOM parsers
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Specifies that the parser produced by this factory will validate documents as they are parsed.
factory.setValidating(false);
// Now use the factory to create a DOM parser
DocumentBuilder parser = factory.newDocumentBuilder();
// Specifies the EntityResolver to resolve DTD used in XML documents
parser.setEntityResolver(new DefaultEntityResolver());
// Specifies the ErrorHandler to handle warning/error/fatalError conditions
parser.setErrorHandler(new DefaultErrorHandler());
return parser;
}
示例5: testEntityExpansionDOMPos
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
/**
* Use a DocumentBuilder to create a DOM object and see if Secure Processing
* feature affects the entity expansion.
*
* @throws Exception If any errors occur.
*/
@Test
public void testEntityExpansionDOMPos() throws Exception {
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setFeature(FEATURE_SECURE_PROCESSING, true);
setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000));
DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
MyErrorHandler eh = new MyErrorHandler();
dBuilder.setErrorHandler(eh);
dBuilder.parse(ENTITY_XML);
assertFalse(eh.isAnyError());
}
示例6: testcase03
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
/**
* Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is
* namespace awareness, DocumentBuilder parse xslt file as DOMSource.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase03() throws Exception {
String outputFile = USER_DIR + "saxtf003.out";
String goldFile = GOLDEN_DIR + "saxtf003GF.out";
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse(new File(XSLT_FILE));
Node node = (Node)document;
DOMSource domSource= new DOMSource(node);
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory)TransformerFactory.newInstance();
TransformerHandler handler =
saxTFactory.newTransformerHandler(domSource);
Result result = new StreamResult(fos);
handler.setResult(result);
reader.setContentHandler(handler);
reader.parse(XML_FILE);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
示例7: writeFile
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
private void writeFile(String title, ArrayList<String> list) throws IOException, ParserConfigurationException, TransformerException {
System.out.println("GetEmoticons.writeFile");
System.out.println("title = " + title);
System.out.println("list = " + list);
if (title == null || list == null || list.isEmpty()) return;
String fileName = title.replaceAll("\\W", "") + ".xml";
File file = new File("C:\\github\\AsciiGenerator\\app\\src\\main\\assets\\emoticons\\" + fileName);
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("root");
document.appendChild(root);
org.w3c.dom.Element name = document.createElement("name");
name.appendChild(document.createTextNode(title));
root.appendChild(name);
org.w3c.dom.Element data = document.createElement("data");
for (String s : list) {
org.w3c.dom.Element item = document.createElement("item");
item.appendChild(document.createTextNode(s));
data.appendChild(item);
}
root.appendChild(data);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(file);
transformer.transform(domSource, streamResult);
}
示例8: parseUserActionResponse
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
private void parseUserActionResponse(String xml){
messageList = new ArrayList<String>();
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
domARB = db.parse(new InputSource(new StringReader(xml)));
domARB.getDocumentElement().normalize();
NodeList nList = domARB.getElementsByTagName("messagetouser");
messageList.clear();
//put all message from server in a list
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
messageList.add(eElement.getTextContent());
}
}
//catch total items returned from server
totalItem=domARB.getElementsByTagName("totalitem").item(0).getTextContent();
}catch(ParserConfigurationException pce) { pce.printStackTrace();
}catch(SAXException se) { se.printStackTrace();
}catch(IOException ioe) { ioe.printStackTrace();
}catch (Exception e){ e.printStackTrace();
}
}
示例9: parse
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
public static XML_Layer parse(InputStream in)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Node root = getElement(dom, "Layers");
XML_Layer layer = parseFolder(root);
layer.name = "Basemaps";
return layer;
}
示例10: createDom
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
/**
* Creates a new DOM document.
*/
public static Document createDom() {
synchronized (DOMUtil.class) {
if (db == null) {
try {
DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory();
dbf.setNamespaceAware(true);
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new FactoryConfigurationError(e);
}
}
return db.newDocument();
}
}
示例11: setupDOMResultHandler
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
/**
* Sets up handler for <code>DOMResult</code>.
*/
private void setupDOMResultHandler(DOMSource source, DOMResult result) throws SAXException {
// If there's no DOMResult, unset the validator handler
if (result == null) {
fDOMValidatorHandler = null;
fSchemaValidator.setDocumentHandler(null);
return;
}
final Node nodeResult = result.getNode();
// If the source node and result node are the same use the DOMResultAugmentor.
// Otherwise use the DOMResultBuilder.
if (source.getNode() == nodeResult) {
fDOMValidatorHandler = fDOMResultAugmentor;
fDOMResultAugmentor.setDOMResult(result);
fSchemaValidator.setDocumentHandler(fDOMResultAugmentor);
return;
}
if (result.getNode() == null) {
try {
DocumentBuilderFactory factory = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
DocumentBuilderFactory.newInstance() : new DocumentBuilderFactoryImpl();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
result.setNode(builder.newDocument());
}
catch (ParserConfigurationException e) {
throw new SAXException(e);
}
}
fDOMValidatorHandler = fDOMResultBuilder;
fDOMResultBuilder.setDOMResult(result);
fSchemaValidator.setDocumentHandler(fDOMResultBuilder);
}
示例12: unsafeManualConfig1
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
public static void unsafeManualConfig1() throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(getInputFile());
print(doc);
}
示例13: extractDocument
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
Document extractDocument(String absolutePath) throws ParserConfigurationException, IOException, SAXException {
//Get the DOM Builder Factory
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
//Load and Parse the XML document
//document contains the complete XML as a Tree.
return builder.parse(readXml(absolutePath));
}
示例14: canonicalize
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
/**
* This method tries to canonicalize the given bytes. It's possible to even
* canonicalize non-wellformed sequences if they are well-formed after being
* wrapped with a <CODE>>a<...>/a<</CODE>.
*
* @param inputBytes
* @return the result of the canonicalization.
* @throws CanonicalizationException
* @throws java.io.IOException
* @throws javax.xml.parsers.ParserConfigurationException
* @throws org.xml.sax.SAXException
*/
public byte[] canonicalize(byte[] inputBytes)
throws javax.xml.parsers.ParserConfigurationException,
java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
InputStream bais = new ByteArrayInputStream(inputBytes);
InputSource in = new InputSource(bais);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
dfactory.setNamespaceAware(true);
// needs to validate for ID attribute normalization
dfactory.setValidating(true);
DocumentBuilder db = dfactory.newDocumentBuilder();
/*
* for some of the test vectors from the specification,
* there has to be a validating parser for ID attributes, default
* attribute values, NMTOKENS, etc.
* Unfortunately, the test vectors do use different DTDs or
* even no DTD. So Xerces 1.3.1 fires many warnings about using
* ErrorHandlers.
*
* Text from the spec:
*
* The input octet stream MUST contain a well-formed XML document,
* but the input need not be validated. However, the attribute
* value normalization and entity reference resolution MUST be
* performed in accordance with the behaviors of a validating
* XML processor. As well, nodes for default attributes (declared
* in the ATTLIST with an AttValue but not specified) are created
* in each element. Thus, the declarations in the document type
* declaration are used to help create the canonical form, even
* though the document type declaration is not retained in the
* canonical form.
*/
db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());
Document document = db.parse(in);
return this.canonicalizeSubtree(document);
}
示例15: transformer04
import javax.xml.parsers.DocumentBuilderFactory; //导入方法依赖的package包/类
/**
* This tests set/get ErrorListener methods of Transformer.
*
* @throws Exception If any errors occur.
*/
@Test
public void transformer04() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File(TEST_XSL));
DOMSource domSource = new DOMSource(document);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(domSource);
transformer.setErrorListener(new MyErrorListener());
assertNotNull(transformer.getErrorListener());
assertTrue(transformer.getErrorListener() instanceof MyErrorListener);
}