繁体   English   中英

将XML字符串作为节点添加到现有XML

[英]Add XML String as Node to Existing XML

我有一个字符串类似xml / mathml的片段,例如<msup><mn>2</mn><mn>6</mn></msup><mo>+</mo><msup><mn>2</mn><mn>7</mn></msup>

我想用此字符串替换现有的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);
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM