Replacing XML node via Java

后端 未结 2 828
情书的邮戳
情书的邮戳 2021-01-18 17:08

I wan to replace a node in XML document with another and as a consequence replace all it\'s children with other content. Following code should work, but for an unknown reaso

相关标签:
2条回答
  • 2021-01-18 17:46

    Try using replaceChild to do the whole hierarchy at once:

    NodeList nodes = doc.getElementsByTagName("NodeToReplace");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Node newNode = // Create your new node here.
        node.getParentNode().replaceChild(newNode, node);
    }
    
    0 讨论(0)
  • 2021-01-18 17:47

    Easy way to do is using regular expression.

    String payload= payload.replaceAll("<payload>([^<]*)</payload>", "<payload>NODATA</payload>");
    

    This will make sure all the payload nodes contents are replaced with NODATA

    0 讨论(0)
提交回复
热议问题