简体   繁体   中英

How to remove first tag from XML file using java

Can anyone please help me how to remove the first tag from a XML file using java?
Remove:

<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?">

from below XML file.

<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?">
<Tag>
    <subTag>tag1</subTag>
    <subTag>tag2</subTag>
</Tag>

Below code:

public class Main
{
    public static void main (String args[])
    {
        File file= new File("XMLfile.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db=factory.newDocumentBuilder();
        Document doc=db.parse(file);
        doc.getDocumentElement().normalize();

        /*remove  <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?"> */
    }
}

Before serialising your XML file give your doc object to a new instance of OutputFormat and then format.setOmitXMLDeclaration(true)

For example:

OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
format.setOmitXMLDeclaration(true);


XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(doc);

Removing the header is valid in XML 1.0, but by doing that, you will lose character encoding data and maybe other things. Please make sure that it is not going to break your system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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