Removes all comment blocks and XML declaration using regex - Java XML

Java examples for XML:XML Comment

Description

Removes all comment blocks and XML declaration using regex

Demo Code

/*******************************************************************************
 * Copyright (c) 2012 DataCite//from   w  ww.  j av  a  2  s.  com
 *
 * All rights reserved. This program and the accompanying 
 * materials are made available under the terms of the 
 * Apache License, Version 2.0 which accompanies 
 * this distribution, and is available at 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String xml = "java2s.com";
        System.out.println(cleanXML(xml));
    }

    /**
     * Removes all comment blocks and XML declaration.
     * @param xml The XML to clean.
     * @return The XML as a string minus comment clocks and XML declaration
     */
    public static String cleanXML(String xml) {
        if (xml == null) {
            return xml;
        } else {
            return xml.replaceAll("(<!--.*-->)", "").replaceAll(
                    "(<\\?xml.*\\?>)", "");
        }
    }
}

Related Tutorials