Strip whitespace and newlines from XML in Java

后端 未结 6 2095
半阙折子戏
半阙折子戏 2020-12-01 21:01

Using Java, I would like to take a document in the following format:


 
    
 
         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 21:38

    recursively traverse the document. remove any text nodes with blank content. trim any text nodes with non-blank content.

    public static void trimWhitespace(Node node)
    {
        NodeList children = node.getChildNodes();
        for(int i = 0; i < children.getLength(); ++i) {
            Node child = children.item(i);
            if(child.getNodeType() == Node.TEXT_NODE) {
                child.setTextContent(child.getTextContent().trim());
            }
            trimWhitespace(child);
        }
    }
    

提交回复
热议问题