remove elements from XML file in java

前端 未结 5 1652
北海茫月
北海茫月 2021-01-23 11:27

I have generated an xml file from an excel data base and it contains automatically an element called \"offset\". To make my new file match my needs, I want to remov

相关标签:
5条回答
  • 2021-01-23 11:42
       String sXML= "<Root><models><id>2</id><modelName>Baseline</modelName><domain_id>2</domain_id><description> desctiption </description><years><Y2013>value1</Y2013><Y2014>value2</Y2014><Y2015>value3</Y2015><Y2016>value4</Y2016><Y2017>value5</Y2017></years><offset/></models></Root>";
       System.out.println(sXML);
       String sNewXML = sXML.replace("<offset/>", "");
       System.out.println(sNewXML);
    
    0 讨论(0)
  • 2021-01-23 11:44

    I would personally recommend using a proper XML parser like Java DOM to check and delete your nodes, rather than dealing with your XML as raw Strings (yuck). Try something like this to remove your 'offset' node.

    File xmlFile = new File("your_xml.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFile);
    
    NodeList nList = doc.getElementsByTagName("offset");
    for (int i = 0; i < nList.getLength(); i++) {
        Node node = nList.item(i);
        node.getParentNode().removeChild(node); 
    }
    

    The above code removes any 'offset' nodes in an xml file.

    If resources/speed considerations are an issue (like when your_xml.xml is huge), you would be better off using SAX, which is faster (a little more code intensive) and doesn't store the XML in memory.

    Once your Document has been edited you'll probably want to convert it to a String to parse to your OutputStream of choice.

    Hope this helps.

    0 讨论(0)
  • 2021-01-23 11:48

    Just try to replace the unwanted string with an empty string. It is quick... and seriously dirty. But might solve your problem quickly... just to reappear later on ;-)

    fileContent.replace("<offset/>, "");

    0 讨论(0)
  • 2021-01-23 11:52
    String xml = "<Root><models><id>2</id><modelName>Baseline</modelName><domain_id>2</domain_id><description> desctiption </description><years><Y2013>value1</Y2013><Y2014>value2</Y2014><Y2015>value3</Y2015><Y2016>value4</Y2016><Y2017>value5</Y2017></years><offset/></models></Root>";
                xml = xml.replaceAll("<offset/>", "");
                System.out.println(xml);
    
    0 讨论(0)
  • 2021-01-23 11:54

    In your original code that you included you have:

    while (fileContent !=null)
    

    Are you initializing fileContent to some non-null value before that line? If not, the code inside your while block will not run.

    But I do agree with the other posters that a simple replaceAll() would be more concise, and a real XML API is better if you want to do anything more sophisticated.

    0 讨论(0)
提交回复
热议问题