Page 1 of 2 12 LastLast
Results 1 to 20 of 25
Like Tree3Likes

Thread: Delete specific lines from an xml file

  1. #1
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Delete specific lines from an xml file

    I have an xml file I want to read, when it hits a specific tag it needs to delete that tag and any after until it reaches the matching end tag like so:
    Java Code:
    <DefaultEnv>
    <car id = "test" >     //finds tag deletes this and any after it 
    <prop 1> colour </prop 1>
    <prop 2> wheels </prop 2>
    </car>                   //deletes this tag and then stops
    </DefaultEnv>
    I'm genuinely quite stuck and I was wondering if anyone could possibly point me in the right direction or even show some sort of example I could go by?
    I understand the logic just not how to delete the lines if the condition is true.

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Delete specific lines from an xml file

    Deleting lines of XML using line based operations is quite tricky since XML is not really line based. There is a structure there, and line breaks are not part of the structure. The XML below is exactly the same to all XML parsers, but will seriously mess you up when you do line based operations:
    Java Code:
    <DefaultEnv><car id = "test" ><prop 1> colour </prop 1><prop 2> wheels </prop 2></car></DefaultEnv>
    You should parse the XML, depending on size using DOM or SAX, then write out the new XML. You might even use XSLT to transform the XML to its new form. Loads of examples are to be found.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    So I need to parse the xml file
    write it to a temp xml file
    then overwrite my original xml with the temp xml?

  4. #4
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Delete specific lines from an xml file

    That sounds like it will work.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  5. #5
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    Thanks for your quick response,you are very helpful! I'm currently reading/writing wish me luck! :P

  6. #6
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Delete specific lines from an xml file

    Good luck! :)
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  7. #7
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    I got it to read my original xml file successfully and write it to a temp file!

    Would I then need to do something to the temp file to remove the environments I don't want in it or should I of done that when reading my original xml file in?

  8. #8
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    25

    Default Re: Delete specific lines from an xml file

    You should be doing that while writing the temp file.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  9. #9
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    I thought as much thank you, suddenly realised after I had got it to write to the temp file. Then I need to overwrite the file - think i'll have to look how to do that!

  10. #10
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Delete specific lines from an xml file

    Here's a simple run down of what I would do:
    - Create a DOMDocument from the source file (DocumentBuilderFactory.newInstance().newDocumentB uilder().parse(file))
    - Modify the DOMDocument to your liking, removing nodes etc.
    - Save the XML to a tempfile (I do that using the code below. Other people may have other methods)
    - Overwrite the original file.

    Java Code:
      public static void saveDocument(Document doc, File file) throws IOException, TransformerException {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            Source source = new DOMSource(doc.getDocumentElement());
            FileOutputStream fos = new FileOutputStream(file);
            Result result = new StreamResult(fos);
            transformer.transform(source, result);
            fos.flush();
            fos.close();
        }
    Fluffy93 likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  11. #11
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    Hi Surfman - that's actually pretty much the same as what I have I have done since last speaking with you! Definitely going to keep a copy of what you have there for my code snippets though just in case I ever need it again!

    The thing I have the most trouble with is actually removing the stuff I want! At the moment I have this:


    Java Code:
                                      if(lines !=null){
    					String trimLine = lines.trim();				
    					if(trimLine.startsWith("Environment id") && trimLine.contains(value)){ //hoping that will get the child node e.g -- <environment id = 'test'>
    
    						arrayList.add(lines);  
    					}
    				}
    Then I use that to create the temp file with xml - Is that code below okay? :)
    Java Code:
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    			Transformer transformer = transformerFactory.newTransformer();
    			DOMSource source = new DOMSource(doc);
    			StreamResult result = new StreamResult(outputFile);
    			//output a message to console to check that the code ran successfully
    			System.out.println("file successfully created");
    
    			//close the writer
    			fw.close();
    			//overwrite original xml file with new file 
    			boolean successful = outputFile.renameTo(inputFile);
    thank you for your kind responses -I'm very appreciative

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Delete specific lines from an xml file

    Are you Alice, over at Code Ranch?

    I seem to be following this conversation from both ends (so to speak)...
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Delete specific lines from an xml file

    You are better off using the DOMDocument for nodes that you don't need and remove those. Deleting lines of XML is very dangerous because of the reasons I mentioned earlier.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  14. #14
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    Hi Tolls,

    Yes I am - I only use these two sites. You must be very confused after reading my posts! :P I'm trying to not keep posting stuff all the time it's just after trial and error and not being able to find much on google the only other people who can offer advice is java programmers here or at code! I do try and help out others in return when I can mind!

  15. #15
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    That makes sense Surfman thank you!

  16. #16
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Delete specific lines from an xml file

    Quote Originally Posted by Fluffy93 View Post
    Hi Tolls,

    Yes I am - I only use these two sites. You must be very confused after reading my posts!
    I thought I had an echo in my mind...:)
    Fluffy93 likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  17. #17
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Delete specific lines from an xml file

    You can even use XPath to find the nodes you're interested in. That saves you from walking the entire tree:
    Java Code:
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    XPathExpression expression = xpath.compile("//car");
    
    NodeList cars= (NodeList) expression.evaluate(document, XPathConstants.NODESET);
    for (int i = 0; i < cars.getLength(); i++) {
        Node car = (Node) cars.item(i);
        System.out.println("Removing car " + car.getAttributes().getNamedItem("id"));
        car.getParentNode().removeChild(car);
    }
    Fluffy93 likes this.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  18. #18
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    Thank you again Surfman I've just been looking at something similar on google! Seriously though thank you for taking the time to explain and provide examples as to what you reference!

    @Tolls whats your name over on code?


    If the child node is <environment id = " ">
    is it correct to do:

    Java Code:
     NodeList node = doc.getElementsByTagName("Environment id");
     for(int x = 0;x < node.getLength();x++){
                        	Element element = (Element) node.item(x);
                        	element.getParentNode().removeChild(element); <-- or would it be element.removeChild(element);
    Last edited by Fluffy93; 10-16-2014 at 04:28 PM.

  19. #19
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Delete specific lines from an xml file

    Quote Originally Posted by Fluffy93 View Post
    @Tolls whats your name over on code?
    I leave that as an exercise for the reader...:)
    But I just stuck a first name on.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  20. #20
    Fluffy93 is offline Member
    Join Date
    Aug 2014
    Posts
    32
    Rep Power
    0

    Default Re: Delete specific lines from an xml file

    Ohhh I spoke to you earlier today didn't I! I know who you are now, you're the man with the sense of humour!

Page 1 of 2 12 LastLast

Similar Threads

  1. delete selected string from all the lines in a text file
    By sreelakshmi.459@gmail.com in forum New To Java
    Replies: 3
    Last Post: 09-19-2013, 09:14 AM
  2. Printing to the screen specific lines from a file
    By stevenhaynes5 in forum New To Java
    Replies: 9
    Last Post: 08-15-2011, 05:28 PM
  3. Read specific lines
    By AA++ in forum New To Java
    Replies: 5
    Last Post: 06-01-2011, 06:11 AM
  4. Replies: 4
    Last Post: 11-03-2010, 06:17 PM
  5. Reading specific lines
    By ivvgangadhar in forum New To Java
    Replies: 8
    Last Post: 01-12-2009, 08:53 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •