简体   繁体   English

如何使用java从XML文件中删除第一个标签

[英]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?谁能帮助我如何使用java从XML文件中删除第一个标签?
Remove:消除:

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

from below XML file.从下面的 XML 文件。

<?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)在序列化您的 XML 文件之前,将您的doc对象提供给OutputFormat的新实例,然后将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.删除标头在 XML 1.0 中是有效的,但这样做会丢失字符编码数据,可能还会丢失其他内容。 Please make sure that it is not going to break your system.请确保它不会破坏您的系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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