java类javax.xml.parsers.DocumentBuilder的实例源码

XMLUtil.java 文件源码 项目:Hydrograph 阅读 34 收藏 0 点赞 0 评论 0
/**
 * 
 * Convert XML string to {@link Document}
 * 
 * @param xmlString
 * @return {@link Document}
 */
public static Document convertStringToDocument(String xmlString) {
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
       DocumentBuilder builder;  
       try 
       {  
        factory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
           builder = factory.newDocumentBuilder();  
           Document doc = builder.parse( new InputSource( new StringReader( xmlString ) ) );            

           return doc;
       } catch (ParserConfigurationException| SAXException| IOException e) {  
        logger.debug("Unable to convert string to Document",e);  
       } 
       return null;
   }
XmlDataContext.java 文件源码 项目:QiuQiu 阅读 18 收藏 0 点赞 0 评论 0
private List<RuleNode> loadXml(String path) throws Exception{
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    builder.setEntityResolver(new UrlDtdPathResolver());
    Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));

    List<RuleNode> results = new ArrayList<>();

    NodeList rootChildren = document.getDocumentElement().getChildNodes();
    for (int i = 0; i < rootChildren.getLength(); i++) {

        Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));

    }

    return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
ModelTranslationService.java 文件源码 项目:redirector 阅读 26 收藏 0 点赞 0 评论 0
public Model translateFlavorRules(SelectServer source, NamespacedListRepository namespacedLists) {
    String flavorRulesXML = getFlavorRulesXML(source);

    Model model = null;
    try {
        if (StringUtils.isNotBlank(flavorRulesXML)) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document newDocument = builder.parse(new ByteArrayInputStream(flavorRulesXML.getBytes(UTF8_CHARSET)));
            model = new Model(newDocument, namespacedLists);
            log.info("Creating model from xml: \n{}", flavorRulesXML);
        } else {
            log.error("Trying to init null model");
        }
    } catch (Exception ex) {
        log.error("Exception while creating model from xml: \n{} \n{}", flavorRulesXML, ex);
    }

    return model;
}
PaymentServiceProviderBean.java 文件源码 项目:oscm 阅读 18 收藏 0 点赞 0 评论 0
private Document createDeregistrationRequestDocument(RequestData data)
        throws ParserConfigurationException,
        PSPIdentifierForSellerException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    Element headerElement = setHeaderXMLParameters(doc);
    setSecurityHeaderXMLParameters(doc, headerElement, data);

    Element transactionElement = setTransactionXMLAttributes(doc,
            headerElement, true, data);

    setIdentificationXMLParameters(doc, transactionElement, data
            .getPaymentInfoKey().longValue(), data.getExternalIdentifier());

    // set the payment code to indicate deregistration
    Element paymentElement = doc
            .createElement(HeidelpayXMLTags.XML_ELEMENT_PAYMENT);
    paymentElement.setAttribute(HeidelpayXMLTags.XML_ATTRIBUTE_CODE,
            getHeidelPayPaymentType(data.getPaymentTypeId()) + ".DR");
    transactionElement.appendChild(paymentElement);
    return doc;
}
Bug4971605.java 文件源码 项目:openjdk-jdk10 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void test1() throws Exception {
    String xsd = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n" + "        xmlns:test='jaxp13_test1'\n"
            + "        targetNamespace='jaxp13_test1'\n" + "        elementFormDefault='qualified'>\n" + "    <element name='test'/>\n" + "</schema>\n";

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Node document = docBuilder.parse(new InputSource(new StringReader(xsd)));
    Assert.assertNotNull(document);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory.newSchema(new Source[] { new DOMSource(document) });
    Assert.assertNotNull(schema, "Failed: newSchema returned null.");
}
BasicParserPool.java 文件源码 项目:lams 阅读 17 收藏 0 点赞 0 评论 0
/** Constructor. */
public BasicParserPool() {
    maxPoolSize = 5;
    builderPool = new Stack<SoftReference<DocumentBuilder>>();
    builderAttributes = new LazyMap<String, Object>();
    coalescing = true;
    expandEntityReferences = true;
    builderFeatures = new LazyMap<String, Boolean>();
    ignoreComments = true;
    ignoreElementContentWhitespace = true;
    namespaceAware = true;
    schema = null;
    dtdValidating = false;
    xincludeAware = false;
    errorHandler = new LoggingErrorHandler(log);

    try {
        dirtyBuilderConfiguration = true;
        initializePool();
    } catch (XMLParserException e) {
        // default settings, no parsing exception
    }
}
Game.java 文件源码 项目:HawkEngine 阅读 25 收藏 0 点赞 0 评论 0
public void LoadCustomBehavior(String filePath, boolean resourcesIncluded)
{
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    Document doc = null;
    try
    {
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(new File((resourcesIncluded ? "Resources/" : "") + filePath));
    } catch (Exception e)
    {
        e.printStackTrace();
        return;
    }

    //TODO: Load into behavior class
}
PersistUtils.java 文件源码 项目:MFM 阅读 25 收藏 0 点赞 0 评论 0
public static void saveDATtoFile(Datafile datafile, String path)
            throws ParserConfigurationException, JAXBException, TransformerException, FileNotFoundException {

        JAXBContext jc = JAXBContext.newInstance(Datafile.class);

        // Create the Document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        DocumentType docType = getDocumentType(document);

        // Marshal the Object to a Document formatted so human readable
        Marshaller marshaller = jc.createMarshaller();
/*
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, docType.getSystemId());
*/

        marshaller.marshal(datafile, document);
        document.setXmlStandalone(true);
        // NOTE could output with marshaller but cannot set DTD document type
/*
        OutputStream os = new FileOutputStream(path);
        marshaller.marshal(datafile, os);
*/

        // Output the Document
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        //    transformerFactory.setAttribute("indent-number", "4");
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        //   transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "8");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
    }
XMLUtil.java 文件源码 项目:emr-nlp-server 阅读 30 收藏 0 点赞 0 评论 0
public static List<String> getModelFnFromXMLList(String fn_xmlList)
        throws Exception {
    List<String> modelNameList = new ArrayList<>();

if (fn_xmlList != null && Util.fileExists(fn_xmlList)) {
    org.w3c.dom.Document dom = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    dom = db.parse(fn_xmlList);
    Element modellistRoot = dom.getDocumentElement();
    NodeList attributeNodes = modellistRoot
            .getElementsByTagName("Attr");

    for (int n = 0; n < attributeNodes.getLength(); n++) {
        Element attributeNode = (Element) attributeNodes.item(n);
        modelNameList.add(attributeNode.getAttribute("fileName").trim());
    }
}

    return modelNameList;
  }
Xml.java 文件源码 项目:OperatieBRP 阅读 31 收藏 0 点赞 0 评论 0
/**
 * Decodeer een object.
 * @param configuration configuratie
 * @param clazz te decoderen object
 * @param reader reader om XML van de lezen
 * @param <T> type van het object
 * @return het gedecodeerde object
 * @throws ConfigurationException bij configuratie problemen (annoties op de klassen)
 * @throws DecodeException bij decodeer problemen
 */
public static <T> T decode(final Configuration configuration, final Class<T> clazz, final Reader reader) throws XmlException {
    final Context context = new Context();
    final Configuration theConfiguration = configuration == null ? DEFAULT_CONFIGURATION : configuration;
    ConfigurationHelper.setConfiguration(context, theConfiguration);

    final Root<T> item = theConfiguration.getModelFor(clazz);

    // Jaxp first
    final Document document;
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        final DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(new InputSource(reader));
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new DecodeException(context.getElementStack(), e);
    }

    return item.decode(context, document);
}


问题


面经


文章

微信
公众号

扫码关注公众号