1

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\"?"> */
    }
}
2
  • 4
    Technically, it's not a tag, it's an XML declaration. It's always helpful to explain WHY you want to do this: if your code is failing because of the presence of the XML declaration, then there is a deeper problem and the "quick fix" of removing the declaration might be inappropriate. Commented Jun 19, 2022 at 8:31
  • FWIW, that XML declaration looks invalid anyway, with all those slashes. But yes, Michael's point above is key here. Commented Jun 19, 2022 at 8:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.