Java XML String Transform normXML(String s)

Here you can find the source of normXML(String s)

Description

norm XML

License

Apache License

Declaration

public static String normXML(String s) 

Method Source Code

//package com.java2s;
/**//from www.  j av a 2s .c  o  m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.StringReader;
import java.io.StringWriter;

import java.util.regex.Pattern;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {
    public static String normXML(String s) {
        String s2 = stripComment(s);
        String s3 = stripProlog(s2);
        try {
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            StringWriter buffer = new StringWriter();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new StreamSource(new StringReader(s3)), new StreamResult(buffer));
            return buffer.toString();
        } catch (Exception e) {
            return "";
        }
    }

    private static String stripComment(String s) {
        return Pattern.compile("<!--(.*?)-->", Pattern.DOTALL).matcher(s).replaceAll("");
    }

    private static String stripProlog(String s) {
        return s.replaceAll("<\\?(.*?)\\?>", "");
    }
}

Related

  1. getXmlStringFromSource(Source payload)
  2. identity(String xml)
  3. indentXML(String fileContent)
  4. loadSourceFromURL(String systemID)
  5. mergeXml(String... xmlSources)
  6. parseEventsToXML(String module, Hashtable keyvalues)
  7. parseToString(final Node node)
  8. parseXmlFile(String filename, boolean validating, boolean namespaceAware)
  9. readFile(String fileName)