⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 e512. converting an xml fragment into a dom fragment.txt

📁 这里面包含了一百多个JAVA源文件
💻 TXT
字号:
This example demonstrates how to parse an XML string fragment into a set of nodes suitable for insertion into a DOM document. 
    // Parses a string containing XML and returns a DocumentFragment
    // containing the nodes of the parsed XML.
    public static DocumentFragment parseXml(Document doc, String fragment) {
        // Wrap the fragment in an arbitrary element
        fragment = "<fragment>"+fragment+"</fragment>";
        try {
            // Create a DOM builder and parse the fragment
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            Document d = factory.newDocumentBuilder().parse(
                new InputSource(new StringReader(fragment)));
    
            // Import the nodes of the new document into doc so that they
            // will be compatible with doc
            Node node = doc.importNode(d.getDocumentElement(), true);
    
            // Create the document fragment node to hold the new nodes
            DocumentFragment docfrag = doc.createDocumentFragment();
    
            // Move the nodes into the fragment
            while (node.hasChildNodes()) {
                docfrag.appendChild(node.removeChild(node.getFirstChild()));
            }
    
            // Return the fragment
            return docfrag;
        } catch (SAXException e) {
            // A parsing error occurred; the xml input is not valid
        } catch (ParserConfigurationException e) {
        } catch (IOException e) {
        }
        return null;
    }

Here's an example that uses the method: 
    // Obtain an XML document; this method is implemented in
    // e510 The Quintessential Program to Create a DOM Document from an XML File
    Document doc = parseXmlFile("infilename.xml", false);
    
    // Create a fragment
    DocumentFragment frag = parseXml(doc, "hello <b>joe</b>");
    
    // Append the new fragment to the end of the root element
    Element element = doc.getDocumentElement();
    element.appendChild(frag);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -