Convert String XML fragment to Document Node in Java

前端 未结 8 2214
迷失自我
迷失自我 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:06

    You can use the document's import (or adopt) method to add XML fragments:

      /**
       * @param docBuilder
       *          the parser
       * @param parent
       *          node to add fragment to
       * @param fragment
       *          a well formed XML fragment
       */
      public static void appendXmlFragment(
          DocumentBuilder docBuilder, Node parent,
          String fragment) throws IOException, SAXException {
        Document doc = parent.getOwnerDocument();
        Node fragmentNode = docBuilder.parse(
            new InputSource(new StringReader(fragment)))
            .getDocumentElement();
        fragmentNode = doc.importNode(fragmentNode, true);
        parent.appendChild(fragmentNode);
      }
    

提交回复
热议问题