473,574 Members | 3,033 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to delete blank lines from xml file by using java

34 New Member
Hi,

I wanted to delete a line from xml file which i did it. But after deletion of that line there is a blank space. Again if i am adding another line by using java that blank line remains as usual.

My xml file is :::::::

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<config>
<employee id = "1" name = "aa" />
<employee id = "2" name = "bb" />
<employee id = "3" name = "cc" />
</config>

For deletion of a line say employee having id = 2 i wrote the following java code:::::
Expand|Select|Wrap|Line Numbers
  1.  
  2.         TransformerFactory transformerFactory = null;
  3.     Transformer transformer = null;
  4.     File file = new File("/src/java/config.xml");
  5.         int employeeNodeLength = 0;
  6.         int idValue = 0;
  7.         try {
  8.         Element employee_elem= null;
  9.         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  10.         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  11.         Document document = documentBuilder.parse(new File("/src/java/config.xml"));
  12.                 NodeList list = document.getElementsByTagName("employee");
  13.         employeeNodeLength = list.getLength();
  14.  
  15.                 for( int i = 0; i < employeeNodeLength ; i++) {
  16.             Node employeeNode= document.getElementsByTagName("employee").item(i);
  17.             NamedNodeMap attributesList = employeeNode.getAttributes();
  18.                     Node employeeId = attributesList.getNamedItem("id");
  19.                     idValue = Integer.parseInt(employeeId.getTextContent());
  20.                     if(idValue == 2) {
  21.                 System.out.println("This "+employeeId.getTextContent()+" node is going to be deleted");
  22.                 employee_elem = (Element)document.getElementsByTagName("employee").item(i);
  23.                 // Remove the node
  24.                 employee_elem.getParentNode().removeChild(employee_elem);
  25.                 // Normalize the DOM tree to combine all adjacent nodes
  26.                 document.normalize();
  27.                 transformerFactory = TransformerFactory.newInstance();
  28.                 transformer = transformerFactory.newTransformer();
  29.                 transformer.setOutputProperty(OutputKeys.INDENT,"no");
  30.                 DOMSource source = new DOMSource(document);
  31.                 StreamResult result =  new StreamResult(file);
  32.                 transformer.transform(source, result);
  33.                 break;
  34.             }
  35.           }
  36.       } catch(Exception e) {
  37.           e.printStackTrace();
  38.       }
  39.  
  40.  
but after deletion of the line id = 2 there is a blank space between two lines employee id =1 and id = 3

I want that after removing one line/lines there should not be any blank space, it should be properly aligned

Thanks in advance
Jun 27 '08 #1
4 25816
venukb
3 New Member
For one, I am not sure why you want to remove the blank lines. The XML parsers will work irrespective of whether there is a new line or not.

If you still intend to "Format" the XML (i.e. indent the XML and remove blank lines), why would you want it to do XML way ? Why not normal String processing ?

Would suggest using Python (Jython) if you intend to just format the XML content.
Jun 28 '08 #2
chaarmann
785 Recognized Expert Contributor
For one, I am not sure why you want to remove the blank lines. The XML parsers will work irrespective of whether there is a new line or not.

If you still intend to "Format" the XML (i.e. indent the XML and remove blank lines), why would you want it to do XML way ? Why not normal String processing ?

Would suggest using Python (Jython) if you intend to just format the XML content.
How to do it with string processing:
a) load the file into a string s
b) use regular expression: s.replace("\\s+ \\n", "\\n");
c) save string s into the old file back.
Jun 30 '08 #3
BibhuAshish
34 New Member
How to do it with string processing:
a) load the file into a string s
b) use regular expression: s.replace("\\s+ \\n", "\\n");
c) save string s into the old file back.
Thanks for your reply.
I know i can delete blank lines by loading file into a string but what i wanted is that if there is any xml parser method through which i can delete.

Any way thanks.
Jun 30 '08 #4
chaarmann
785 Recognized Expert Contributor
Thanks for your reply.
I know i can delete blank lines by loading file into a string but what i wanted is that if there is any xml parser method through which i can delete.

Any way thanks.
ok.
I did not try your program, but from my experience I can tell that a blank line is an empty node that you should remove, too.
Try to get the number of nodes for the parent. If you have more than you have lines of employees, then you probably have additional blank lines which also count as elements. That means:
employee1, blank, employee2, blank, employee3 and so on.

As I said, I have not yet tried your code, I am just guessing.
But I concluded from my experience in Javascript when building up the DOM structure from XML in Ajax for different web browsers: One browser makes these addditional blank elements, the other not.
Jun 30 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1367
by: Row | last post by:
HI, I would first like to say its been about 3 years since looking at java im very rusty! I have to write a post it notes type applet which will function online. (reading from a flat text file) My main problem is: getting each paragraph into my vector array - so that each paragraph sits in a new array element. Eg: when i referance array...
23
8921
by: da Vinci | last post by:
Greetings, Onwards with the school studying. Working on a program and need to delete a file from a known location on the hard drive but cannot get anything I do to work. I have tried to use the remove function that is included with <cstdio> but cannot get it to work properly. My reference book has the following....
16
16994
by: Philip Boonzaaier | last post by:
I want to be able to generate SQL statements that will go through a list of data, effectively row by row, enquire on the database if this exists in the selected table- If it exists, then the colums must be UPDATED, if not, they must be INSERTED. Logically then, I would like to SELECT * FROM <TABLE> WHERE ....<Values entered here>, and then...
4
3224
by: Ryan S | last post by:
I am trying to read an XML document generated by a web server using the XMLTextReader class, but the document generated appears to have some blank lines at the top that are causing problems. If I connect directly to the URL, when I call the ".Read" method on the XMLTextReader, I get the message: "The XML declaration is unexpected. Line...
5
9917
by: Neil | last post by:
I am getting time-out errors when I try to perform a simple delete on a linked server. The command is: Delete From MyTable Where PKID=12345 I have tried executing this command directly from Query Analyzer, but it just times out. However, when I run it from QA against the server itself (rather than from my local server against a linked...
6
9969
by: EricR | last post by:
I am trying to bcp import a text file into a SQL Server 2000 database. The text file is coming out of a java application where order information is written to the text file. Each record is on it's own row, so the last item in each record has a new line character at the end of it to create the next row. This works well in creating the file...
2
19734
by: Francesco Pietra | last post by:
Please, how to adapt the following script (to delete blank lines) to delete lines containing a specific word, or words? f=open("output.pdb", "r") for line in f: line=line.rstrip() if line: print line f.close()
0
2071
by: Francesco Pietra | last post by:
I forgot to add that the lines to strip are in present case of the type of the following block HETATM 7007 O WAT 446 27.622 34.356 55.205 1.00 0.00 O HETATM 7008 H1 WAT 446 27.436 34.037 56.145 1.00 0.00 H HETATM 7009 H2 WAT 446 27.049 33.827 54.563 1.00 0.00 H ...
6
5848
by: Annalyzer | last post by:
My database must produces a .csv file with a header line that is different from the detail lines. This .csv file contains a monthly report to an outside agency and is uploaded online so it must follow specific guidelines. As usual, I think I have made the processing way more convoluted than necessary. Here is what I have currently: 1)...
0
7758
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8100
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7856
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6509
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5335
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3793
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2270
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1099
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.