Convert String XML fragment to Document Node in Java

前端 未结 8 2135
迷失自我
迷失自我 2020-11-28 04:00

In Java how can you convert a String that represents a fragment of XML for insertion into an XML document?

e.g.

String newNode =  \"valu         


        
相关标签:
8条回答
  • 2020-11-28 04:10
    Element node =  DocumentBuilderFactory
        .newInstance()
        .newDocumentBuilder()
        .parse(new ByteArrayInputStream("<node>value</node>".getBytes()))
        .getDocumentElement();
    
    0 讨论(0)
  • 2020-11-28 04:12
    /**
    *
    * Convert a string to a Document Object
    *
    * @param xml The xml to convert
    * @return A document Object
    * @throws IOException
    * @throws SAXException
    * @throws ParserConfigurationException
    */
    public static Document string2Document(String xml) throws IOException, SAXException, ParserConfigurationException {
    
        if (xml == null)
        return null;
    
        return inputStream2Document(new ByteArrayInputStream(xml.getBytes()));
    
    }
    
    
    /**
    * Convert an inputStream to a Document Object
    * @param inputStream The inputstream to convert
    * @return a Document Object
    * @throws IOException
    * @throws SAXException
    * @throws ParserConfigurationException
    */
    public static Document inputStream2Document(InputStream inputStream) throws IOException, SAXException, ParserConfigurationException {
        DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
        newInstance.setNamespaceAware(true);
        Document parse = newInstance.newDocumentBuilder().parse(inputStream);
        return parse;
    }
    
    0 讨论(0)
提交回复
热议问题