将XML String作为节点添加到现有XML

时间:2017-04-27 12:16:33

标签: java xml

我有一个像<msup><mn>2</mn><mn>6</mn></msup><mo>+</mo><msup><mn>2</mn><mn>7</mn></msup>

这样的字符串中的xml / mathml片段

我想用这个字符串替换现有的xml节点。我试过了

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuild = docFactory.newDocumentBuilder();
    Document doc = docBuild.parse(is); //is ==> Inputstream
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new Namespace());
    XPathExpression expr = xpath.compile(xPath); //xPath ==>XPath of parent node where the above is to be appended
    Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
    if (node.getChildNodes().item(0).getNodeName().equals("mml:math")) {
        node.removeChild((node.getChildNodes().item(0)));
        Element s= doc.createElement("mml:math");
        s.setNodeValue("<msup><mn>2</mn><mn>6</mn></msup><mo>+</mo><msup><mn>2</mn><mn>7</mn></msup>");
        node.appendChild(s);
    }

1 个答案:

答案 0 :(得分:0)

我没有使用s.setNodeValue(),而是使用s.setTextContent()解决了我的问题。