当前位置: 首页>>代码示例>>Java>>正文


Java DocumentBuilderFactory.newDocumentBuilder方法代码示例

本文整理汇总了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;
    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:TransformerFactoryTest.java

示例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);
  }

}
 
开发者ID:naver,项目名称:hadoop,代码行数:23,代码来源:TestHsWebServicesJobs.java

示例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;
	}
 
开发者ID:dvbern,项目名称:doctemplate,代码行数:17,代码来源:DOCXMergeEngine.java

示例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;
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:23,代码来源:AbstractLoader.java

示例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());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:AuctionItemRepository.java

示例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));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:32,代码来源:SAXTFactoryTest.java

示例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);
}
 
开发者ID:tranleduy2000,项目名称:ascii_generate,代码行数:34,代码来源:GetEmoticons.java

示例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();
	}
}
 
开发者ID:anirban99,项目名称:Shopping-Cart-using-Web-Services,代码行数:28,代码来源:MyClientRest.java

示例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;
}
 
开发者ID:iedadata,项目名称:geomapapp,代码行数:13,代码来源:XML_Layer.java

示例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();
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:18,代码来源:DOMUtil.java

示例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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:36,代码来源:DOMValidatorHelper.java

示例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);
}
 
开发者ID:blackarbiter,项目名称:Android_Code_Arbiter,代码行数:12,代码来源:DocumentBuilderSafeProperty.java

示例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));
    }
 
开发者ID:DonutReport,项目名称:donut-nunit-adapter,代码行数:14,代码来源:NUnitAdapter.java

示例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>&gt;a&lt;...&gt;/a&lt;</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);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:54,代码来源:Canonicalizer.java

示例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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:TransformerTest.java


注:本文中的javax.xml.parsers.DocumentBuilderFactory.newDocumentBuilder方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。