Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#newDocumentBuilder()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#newDocumentBuilder() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static void main(String argv[]) {
 
try {
	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	Document doc = docBuilder.parse(ClassLoader.getSystemResourceAsStream("books.xml"));

	NodeList list = doc.getElementsByTagName("book");

	System.out.println("Total of elements : " + list.getLength());

} catch (ParserConfigurationException pce) {
	pce.printStackTrace();
} catch (IOException ioe) {
	ioe.printStackTrace();
} catch (SAXException sae) {
	sae.printStackTrace();
}
 }
 
Example 2
public DOMForest(InternalizationLogic logic, @NotNull EntityResolver entityResolver, WsimportOptions options, ErrorReceiver errReceiver) {
    this.options = options;
    this.entityResolver = entityResolver;
    this.errorReceiver = errReceiver;
    this.logic = logic;
    try {
        // secure xml processing can be switched off if input requires it
        boolean secureProcessingEnabled = options == null || !options.disableXmlSecurity;
        DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory(secureProcessingEnabled);
        dbf.setNamespaceAware(true);
        this.documentBuilder = dbf.newDocumentBuilder();

        this.parserFactory = XmlUtil.newSAXParserFactory(secureProcessingEnabled);
        this.parserFactory.setNamespaceAware(true);
    } catch (ParserConfigurationException e) {
        throw new AssertionError(e);
    }
}
 
Example 3
Source Project: PolyGlot   File: CustHandlerFactory.java    License: MIT License 6 votes vote down vote up
/**
 * Creates appropriate handler to read file (based on version of PolyGlot
 * file was saved with)
 *
 * @param iStream stream of file to be loaded
 * @param core dictionary core
 * @return an appropriate handler for the xml file
 * @throws java.lang.Exception when unable to read given file or if file is
 * from newer version of PolyGlot
 */
public static CustHandler getCustHandler(InputStream iStream, DictCore core) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc;

    doc = dBuilder.parse(iStream);
    doc.getDocumentElement().normalize();

    // test for version number in pgd file, set to 0 if none found (pre 0.6)
    Node versionNode = doc.getDocumentElement().getElementsByTagName(PGTUtil.PGVERSION_XID).item(0);
    String versionNumber = versionNode == null ? "0" : versionNode.getTextContent();
    int fileVersionHierarchy = PGTUtil.getVersionHierarchy(versionNumber);
    
    if (fileVersionHierarchy == -1) {
        throw new Exception("Please upgrade PolyGlot. The PGD file you are loading was "
                    + "written with a newer version with additional features: Ver " + versionNumber + ".");
    } else if (fileVersionHierarchy < PGTUtil.getVersionHierarchy("0.7.5")) {
        throw new Exception("Version " + versionNumber + " no longer supported. Load/save with older version of "
                    + "PolyGlot (0.7.5 through 1.2) to upconvert.");
    }

    return get075orHigherHandler(core, fileVersionHierarchy);
}
 
Example 4
Source Project: util   File: XMLUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据xml内容直接生成xml dom
 * @param xmlContent xml内容
 * @throws ParserConfigurationException 
 * @throws IOException 
 * @throws SAXException 
 */
public XMLUtil(String xmlContent) throws ParserConfigurationException, SAXException, IOException{
	StringReader sr = new StringReader(xmlContent);
	InputSource is = new InputSource(sr); 
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	//不检查DTD
	db.setEntityResolver( new EntityResolver() {
		 public InputSource resolveEntity(String publicId, String systemId)  
		         throws SAXException, IOException {                   
			   return new InputSource(new StringReader(""));
		 }
		}   
	);
	//读取文件
	doc=db.parse(is);
}
 
Example 5
public void parse(InputStream document, OutputStream finf, String workingDirectory) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    if (workingDirectory != null) {
        db.setEntityResolver(createRelativePathResolver(workingDirectory));
    }
    Document d = db.parse(document);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.transform(new DOMSource(d), new FastInfosetResult(finf));
}
 
Example 6
public HashMap<String, String> parseXml(InputStream inStream) throws Exception {
    HashMap<String, String> hashMap = new HashMap<String, String>();

    // 实例化一个文档构建器工厂
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // 通过文档构建器工厂获取一个文档构建器
    DocumentBuilder builder = factory.newDocumentBuilder();
    // 通过文档通过文档构建器构建一个文档实例
    Document document = builder.parse(inStream);
    //获取XML文件根节点
    Element root = document.getDocumentElement();
    //获得所有子节点
    NodeList childNodes = root.getChildNodes();
    for (int j = 0; j < childNodes.getLength(); j++) {
        //遍历子节点
        Node childNode = (Node) childNodes.item(j);
        if (childNode.getNodeType() == Node.ELEMENT_NODE) {
            Element childElement = (Element) childNode;
            //版本号
            if ("version".equals(childElement.getNodeName())) {
                hashMap.put("version", childElement.getFirstChild().getNodeValue());
            }
            //软件名称
            else if (("name".equals(childElement.getNodeName()))) {
                hashMap.put("name", childElement.getFirstChild().getNodeValue());
            }
            //下载地址
            else if (("url".equals(childElement.getNodeName()))) {
                hashMap.put("url", childElement.getFirstChild().getNodeValue());
            }
        }
    }
    return hashMap;
}
 
Example 7
Source Project: xmlunit   File: ValueAssertTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsEqualTo_withAttributeValueExpression_fromElementClass_shouldPass() throws Exception {

    String xml = "<a><b attr=\"abc\"></b></a>";

    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    f.setNamespaceAware(true);
    DocumentBuilder db = f.newDocumentBuilder();
    Element xmlRootElement = db.parse(new InputSource(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))).getDocumentElement();

    assertThat(xmlRootElement).valueByXPath("//a/b/@attr").isEqualTo("abc");
}
 
Example 8
Source Project: BotLibre   File: LoginBean.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public boolean importTranslations(InputStream stream) {
	try {
		checkLogin();
		checkSuper();
		String text = Utils.loadTextFile(stream, "", Site.MAX_UPLOAD_SIZE);
		if (text == null) {
			throw new BotException("Invalid file");
		}
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder parser = factory.newDocumentBuilder();
		StringReader reader = new StringReader(text);
		InputSource source = new InputSource(reader);
		Document document = parser.parse(source);
		Element root = document.getDocumentElement();
		List<Element> translations = getLocalElementsByTagName("translation", root);
		for (Element element : translations) {
			Translation translation = new Translation();
			translation.parseXML(element);
			AdminDatabase.instance().updateTranslation(translation);
			TranslationService.instance().clear(translation);
		}			
	} catch (Exception failed) {
		error(new BotException(failed.toString()));
		return false;
	}
	return true;
}
 
Example 9
/** Initializes the document set, given a TAC2008 topic XML file.
 * 
 * @param sXMLFile The filename of the topic file.
 * @param sCorpusRootDir The base directory of the TAC2008 test corpus 
 * directory structure.
 */
public TAC2008TopicFileSet(String sTopicXMLFile, String sCorpusRootDir) 
        throws ParserConfigurationException, SAXException, IOException {
    TopicFile = sTopicXMLFile;
    CorpusDir = sCorpusRootDir;
    // Init XML doc file
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    TopicXMLDoc = docBuilder.parse(new File(sTopicXMLFile));
    
    Categories = null;
    TrainingFiles = null;
    TestFiles = null;
}
 
Example 10
@Test
public void testNormal() throws ParserConfigurationException, SAXException, IOException {
	try {
		WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, corpId);
		String afterEncrpt = pc.EncryptMsg(replyMsg, timestamp, nonce);

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		StringReader sr = new StringReader(afterEncrpt);
		InputSource is = new InputSource(sr);
		Document document = db.parse(is);

		Element root = document.getDocumentElement();
		NodeList nodelist1 = root.getElementsByTagName("Encrypt");
		NodeList nodelist2 = root.getElementsByTagName("MsgSignature");

		String encrypt = nodelist1.item(0).getTextContent();
		String msgSignature = nodelist2.item(0).getTextContent();
		String fromXML = String.format(xmlFormat, encrypt);

		// 第三方收到公众号平台发送的消息
		String afterDecrpt = pc.DecryptMsg(msgSignature, timestamp, nonce, fromXML);
		assertEquals(replyMsg, afterDecrpt);
	} catch (AesException e) {
		fail("正常流程,怎么就抛出异常了??????");
	}
}
 
Example 11
/**
 * @see org.sakaiproject.api.app.help.RestConfiguration#getResourceNameFromCorpusDoc(java.lang.String)
 */
public String getResourceNameFromCorpusDoc(String xml)
{
  try
  {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    StringReader sReader = new StringReader(xml);
    InputSource inputSource = new org.xml.sax.InputSource(sReader);
    org.w3c.dom.Document xmlDocument = builder.parse(inputSource);
    sReader.close();
    
    NodeList nodeList = xmlDocument.getElementsByTagName("kbq");
    
    int nodeListLength = nodeList.getLength();
    for (int i = 0; i < nodeListLength; i++){
      Node currentNode = nodeList.item(i);
      
      NodeList nlChildren = currentNode.getChildNodes();
      
      for (int j = 0; j < nlChildren.getLength(); j++){
        if (nlChildren.item(j).getNodeType() == Node.TEXT_NODE){
          return nlChildren.item(j).getNodeValue();
        }
      }
    }
    return null;
  }            
  catch (Exception e)
  {
    log.error(e.getMessage(), e);
  }     
  
  return null;
}
 
Example 12
public void testGenerationWithAllInfoInDescriptor()
    throws Exception
{
    runTest( "generic", "src/test/resources/project-1/pom.xml", "src/test/resources/project-1/descriptor.xml",
             "target/output-1-generic" );

    File actualAppXml = new File( getTestFile( "target/output-1-generic" ), "app.xml" );

    assertTrue( "config file is missing: " + actualAppXml.getAbsolutePath(), actualAppXml.isFile() );

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    builderFactory.setIgnoringComments( true );
    builderFactory.setIgnoringElementContentWhitespace( true );
    DocumentBuilder builder = builderFactory.newDocumentBuilder();

    Document actual = builder.parse( actualAppXml );

    assertNodeEquals( "com.westerngeco.example.App", "mainClass", actual );
    assertNodeEquals( "org/codehaus/mojo/appassembler/project-1/1.0-SNAPSHOT/project-1-1.0-SNAPSHOT.jar",
                      "relativePath", actual );
    assertNodeEquals( "345", "initialMemorySize", actual );
    assertNodeEquals( "234", "maxMemorySize", actual );
    assertNodeEquals( "321", "maxStackSize", actual );
    assertNodeEquals( "foo=bar", "systemProperty", actual );
    assertNodeEquals( "arg1=arg1-value", "commandLineArgument", actual );
    assertNodeNull( "commandLineArgument", actual );

}
 
Example 13
Source Project: java-n-IDE-for-Android   File: XmlUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given XML string as a DOM document, using the JDK parser. The parser does not
 * validate, and is optionally namespace aware.
 *
 * @param xml            the XML content to be parsed (must be well formed)
 * @param namespaceAware whether the parser is namespace aware
 * @return the DOM document
 */
@NonNull
public static Document parseDocument(@NonNull String xml, boolean namespaceAware)
        throws ParserConfigurationException, IOException, SAXException {
    xml = stripBom(xml);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    InputSource is = new InputSource(new StringReader(xml));
    factory.setNamespaceAware(namespaceAware);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(is);
}
 
Example 14
private Document emptyDocument() throws ParserConfigurationException {
  DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
  Document metadataDocument = docBuilder.newDocument();
  return metadataDocument;
}
 
Example 15
Source Project: Despector   File: EclipseFormatLoader.java    License: MIT License 4 votes vote down vote up
@Override
public void load(EmitterFormat format, Path formatter, Path import_order) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader(import_order.toFile()))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("#")) {
                continue;
            }
            String[] parts = line.split("=");
            int part;
            String path;
            if (parts.length == 1) {
                part = Integer.parseInt(parts[0]);
                path = "";
            } else if (parts.length == 2) {
                part = Integer.parseInt(parts[0]);
                path = parts[1];
            } else {
                System.err.println("Malformed importorder file");
                continue;
            }
            if (part < format.import_order.size()) {
                format.import_order.set(part, path);
            } else {
                while (part > format.import_order.size()) {
                    format.import_order.add(null);
                }
                format.import_order.add(path);
            }
        }
    }

    DocumentBuilderFactory db_factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder doc_builder = db_factory.newDocumentBuilder();
        Document doc = doc_builder.parse(formatter.toFile());
        doc.getDocumentElement().normalize();
        Element profiles = (Element) doc.getElementsByTagName("profiles").item(0);
        Element profile = (Element) profiles.getElementsByTagName("profile").item(0);
        NodeList settings = profile.getElementsByTagName("setting");
        for (int i = 0; i < settings.getLength(); i++) {
            Element setting = (Element) settings.item(i);
            String id = setting.getAttribute("id");
            String value = setting.getAttribute("value");
            BiConsumer<EmitterFormat, String> handler = settings_handlers.get(id);
            if (handler == null) {
                continue;
            }
            handler.accept(format, value);
        }

    } catch (Exception e) {
        System.err.println("Error loading formatter xml:");
        e.printStackTrace();
    }
}
 
Example 16
Source Project: localization_nifi   File: FlowParser.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts
 * the root group input ports and output ports, and their access controls.
 *
 */
public FlowInfo parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
         final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        // create validating document builder
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(flowSchema);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));

        // extract the root group id
        final Element rootElement = document.getDocumentElement();

        final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0);
        if (rootGroupElement == null) {
            logger.warn("rootGroup element not found in Flow Configuration file");
            return null;
        }

        final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0);
        if (rootGroupIdElement == null) {
            logger.warn("id element not found under rootGroup in Flow Configuration file");
            return null;
        }

        final String rootGroupId = rootGroupIdElement.getTextContent();

        final List<PortDTO> ports = new ArrayList<>();
        ports.addAll(getPorts(rootGroupElement, "inputPort"));
        ports.addAll(getPorts(rootGroupElement, "outputPort"));

        return new FlowInfo(rootGroupId, ports);

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}
 
Example 17
Source Project: JDKSourceCode1.8   File: Canonicalizer.java    License: MIT License 4 votes vote down vote up
/**
 * 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);
}
 
Example 18
Source Project: feeyo-hlsserver   File: ConfigLoader.java    License: Apache License 2.0 4 votes vote down vote up
private static Document loadXmlDoc(String uri) throws Exception {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(uri);
	return doc;
}
 
Example 19
protected static Document loadXmlDoc(String uri) throws Exception {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(uri);
	return doc;
}
 
Example 20
Source Project: org.hl7.fhir.core   File: XMLUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static Document parseToDom(String content) throws ParserConfigurationException, SAXException, IOException  {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(false);
  DocumentBuilder builder = factory.newDocumentBuilder();
  return builder.parse(new ByteArrayInputStream(content.getBytes()));
}