473,785 Members | 2,738 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 25936
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 elemant 2 it will give me paragraph which is in that element and not all paragraphs in the text file...
23
8948
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
17019
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 IF FOUND UPDATE <TABLE> SET .... <Values entered here> ELSE INSERT INTO <TABLE> VALUES <Values...
4
3238
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 8, Column 3" If I open the URL in my browser and copy and paste the XML stuff (starting
5
9937
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 server), it executes immediately. Similarly, if I run the same SQL command through an ODBC linked...
6
9997
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 however bcp does not like to import this text file with the extra blank line at the end. If I change...
2
19754
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
2090
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 occurring in a 300MB file. In present case each three-lines block is followed by line renumbering (7007,
6
5869
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) Macro #1 runs query #1 to create (or overwrite) a table with the current month's header information....
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10319
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10087
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9947
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8971
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7496
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6737
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.