Solved

java and xml file

Posted on 2004-04-25
42
279 Views
Last Modified: 2010-03-31
I have a many xml files in a folder on my machine, is there a way I can output the names of the files to the screen where the <a> tag is 5.

<emp>
  <des>
    <nam>name</nam>
    <a>5</a>
  </des>
</emp>
0
Comment
Question by:pentiumnewbie
  • 15
  • 14
  • 12
  • +1
42 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
You could do something like this:

File f = new File("yourXmlDir");
File[] xmlFiles = f.listFiles();
boolean[] found = new boolean(xmlFiles.length);

// read thus but in a loop with index 'i'

try {
        BufferedReader in = new BufferedReader(new FileReader(xmlFiles[i]));
        String str;
        while ((str = in.readLine()) != null) {
            if(foundTag(str)) {
                  found[i] = true;
                  break;
            }
        }
        in.close();
    } catch (IOException e) {
    }
   
   
public boolean foundTag(String s) {
      return s.indexOf("<a>") > -1 && s.indexOf("5") > -1;
}
0
 

Author Comment

by:pentiumnewbie
Comment Utility
When I say name I mean this value:

<nam>name</nam>

Thank you.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
You've lost me...
0
 

Author Comment

by:pentiumnewbie
Comment Utility
I just want to output this tag : <nam>name</nam> where <a> is 5

<emp>
  <des>
    <nam>name</nam>
    <a>5</a>
  </des>
</emp>
0
 

Author Comment

by:pentiumnewbie
Comment Utility
Ive tried tweaking your code to suit me and this is what I have came up with, it runs but does'nt seem to find the relevant files


int i = 0;
File f = new File("myfile");
File[] xmlFiles = f.listFiles();
boolean[] found = new boolean[xmlFiles.length];


        BufferedReader in = new BufferedReader(new FileReader(xmlFiles[i]));
        String str;
        while ((str = in.readLine()) != null) {
       
            if(str.indexOf("<a>") > -1 && str.indexOf("5") > -1) {
                 found[i] = true;
                    System.out.print("pending");
                 break;
               
            }
        }
        in.close();
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
So far, you are only looking at the first file - there's no loop
0
 

Author Comment

by:pentiumnewbie
Comment Utility
This should work?

 for(int cnt = 0; cnt < xmlFiles.length + 1; ++cnt){
while ((str = in.readLine()) != null) {
       
            if(str.indexOf("<a>") > -1 && str.indexOf("5") > -1) {
                 found[i] = true;
                    System.out.print("pending");
                 break;
               
            }
        }

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> So far, you are only looking at the first file - there's no loop

its *your* code :)

try the following to go thru all files:

int i = 0;
File f = new File("myfile");
File[] xmlFiles = f.listFiles();
boolean[] found = new boolean[xmlFiles.length];
for (int i=0; i<xmlFiles.length; i++)
{
        BufferedReader in = new BufferedReader(new FileReader(xmlFiles[i]));
        String str;
        while ((str = in.readLine()) != null) {
       
            if(str.indexOf("<a>") > -1 && str.indexOf("5") > -1) {
                 found[i] = true;
                    System.out.print("pending");
                 break;
               
            }
        }
        in.close();
}
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>for(int cnt = 0; cnt < xmlFiles.length + 1; ++cnt){

should be

for(int cnt = 0; cnt < xmlFiles.length; cnt++){
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>its *your* code :)

Please read the question thread before commenting

>>// read thus but in a loop with index 'i'
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
i did read the question, the comment didn't seem all that useful
and took more typing than the actual code :)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>i did read the question, the comment didn't seem all that useful

If the code doesn't work as a result of ignoring it, then i think that implies it IS useful
0
 

Author Comment

by:pentiumnewbie
Comment Utility

that worked,
for(int cnt = 0; cnt < xmlFiles.length; cnt++){
Will the last file be missed?
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
will all the xml files have the same structure?
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> Will the last file be missed?

no
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
This will do what you *actually* want to do - you need (if necessary) to read the file twice:

for (int i=0; i<xmlFiles.length; i++) {
        String values[] = new String[xmlFiles.length];
      boolean aIsFive = false;
        BufferedReader in = new BufferedReader(new FileReader(xmlFiles[i]));
        in.mark((int)xmlFiles[i].length());
        String str = null;
        while ((str = in.readLine()) != null) {
            if(str.indexOf("<a>") > -1 && str.indexOf("5") > -1) {
                 aIsFive = true;
                 break;
            }
        }
        if (aIsFive) {
              in.reset();
              // READ THE FILE AGAIN AND GET THE VALUE OF <nam> AS BEFORE
              // PUT THE VALUE OF <nam> in values[i]
        }
        else {
              in.close();
        }
}
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Whoops

>>String values[] = new String[xmlFiles.length];

should be *before* the loop
0
 

Author Comment

by:pentiumnewbie
Comment Utility
>> When I say name I mean this value:
<nam>name</nam>

 I want to output the value in this tag : <nam>name</nam>.
Thats what I was trying to get across before
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
theres no need to read the file twice.
I'll let you CEHJ show you how.

let me know if u need any more help :)
0
 

Author Comment

by:pentiumnewbie
Comment Utility
>> will all the xml files have the same structure?
yes,

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
i'd use a different approach to your problem than has been posted, let me know if u are interested.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:pentiumnewbie
Comment Utility

Basically, i want to access the values within the tags.

Will this work?
str.valueOf(<nam>);
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
It's not particularly safe, but if each file has *exactly* the same format (with nam on the previous line) you can simply save the previous line read and substring it for the value. Then you wouldn't have to read it twice
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
The 'proper' way to do what you want to do is to use XPath, but to use that you'd either need a 3rd party library or to upgrade to SDK 1.5
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> you can simply save the previous line read and substring it for the value. Then you wouldn't have to read it twice

come on u can do it a lot easier than that :)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>str.valueOf(<nam>);

You need

String namValue = str.substring(str.indexOf("<nam>"), str.indexOf("</nam>"));
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> The 'proper' way to do what you want to do is to use XPath

there are a variety of approaches that could be used
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Since you have small files you may as well read the whole file into a StringBuffer and then substring it after toString()
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
pentiumnewbie,

Is this all helping you?
0
 

Author Comment

by:pentiumnewbie
Comment Utility
What could I add to the following to get the value?

String t = domNode.getNodeValue().trim();
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
Have you given up on CEHJ's suggested approach?
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
if that node is 'a' then you can do

String namValue = domNode.getPreviousSibling().getNodeValue().trim();
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 25 total points
Comment Utility
If you want to do the text file thing, this should work:

for (int i=0; i<xmlFiles.length; i++) {
        String values[] = new String[xmlFiles.length];
      boolean aIsFive = false;
        BufferedReader in = new BufferedReader(new FileReader(xmlFiles[i]));
        StringBuffer sb = new StringBuffer((int)xmlFiles[i].length());
        int buf= -1;
        while ((buf = in.read()) > -1) {
            sb.append((char)buf);
        }
        in.close();
        String contents = sb.toString();
        if (contents.indexOf("<a>5</a>") > -1) {
              values[i] = contents.substring(contents.indexOf("<nam>"), contents.indexOf("</nam>"));
        }
}
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
this is getting painful :) theres no need to read the file twice or read the entire file into memory.
try the following:

import java.io.*;

public class ParseXML
{
      public static void main(String[] args) throws IOException
      {
            File f = new File(args[0]);
            File[] xml = f.listFiles();
             for (int i=0; i<xml.length; i++)
            {
                  String nam = parse(xml[i]);
                  if (nam!=null)
                  {
                        System.out.println(nam);
                  }
            }
      }
      
      private static String parse(File f) throws IOException
      {
            int a = 0;
            String nam = null;
        BufferedReader in = new BufferedReader(new FileReader(f));
        String line = null;
        while (null!=(line = in.readLine()))
        {
              line = line.trim();
              if (line.equals("<a>5</a>"))
              {
                    a = 5;
              }
              else if (line.startsWith("<nam>"))
              {
                    nam = line.substring(5, line.indexOf("</nam>"));

              }
        }
        return a==5 ? nam : null;
      }
}
0
 

Author Comment

by:pentiumnewbie
Comment Utility

Thanks for all your help, i think im nearly done, below is what i have, but this does'nt work:
String nam = str.substring(8, str.indexOf("</Status>"));
                           out.print(nam);
/////////////////////////////////////////////////////////////////////////////

File[] xmlFiles = f.listFiles();
boolean[] found = new boolean[xmlFiles.length];
for (int i=0; i<xmlFiles.length; i++)
{
        BufferedReader in = new BufferedReader(new FileReader(xmlFiles[i]));
        String str;
        while ((str = in.readLine()) != null) {

            if(str.indexOf("<Status>") > -1 && str.indexOf("1") > -1) {
            if (str.startsWith("<Status>"))
                             {
                           String nam = str.substring(8, str.indexOf("</Status>"));
                           out.print(nam);
                   }
                 found[i] = true;
   
                 break;
               
            }
        }
0
 
LVL 92

Assisted Solution

by:objects
objects earned 25 total points
Comment Utility
see the code I posted above, it provides a method to extract nam when a=5
0
 

Author Comment

by:pentiumnewbie
Comment Utility
Thanks for your help and your patience :)

Its working now and this is what im using:
String idnum = (String)session.getAttribute("idnum");
File f = new File("\\seanproj\\Orders\\Pending");

File[] xmlFiles = f.listFiles();
boolean[] found = new boolean[xmlFiles.length];
for (int i=0; i<xmlFiles.length; i++)
{
        BufferedReader in = new BufferedReader(new FileReader(xmlFiles[i]));
        String str;
        while ((str = in.readLine()) != null) {

            if(str.indexOf("<Status>") > -1 && str.indexOf("1") > -1) {
 
                           String status = str.substring(12, str.indexOf("</Status>"));
                           out.println(status);
                     
                  
                 found[i] = true;
   
                 break;
               
            }
        }
        in.close();
       
 
}
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
sorry for all the stuffing around :)
0
 

Author Comment

by:pentiumnewbie
Comment Utility
No bother at all, i should do some of the work :)

Thanks again
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)

>>Its working now and this is what im using:

Of course, you can now put the value of 'status' in a String array per my earlier post instead of putting found in a boolean array. Unfound ones would stay null in the array
0
 
LVL 7

Expert Comment

by:searlas
Comment Utility
objects,

I found your baiting of CEHJ most entertaining... but...

Your parse method sets a to 5 when it first encounters a line containing <a>5</a>.  It then returns the name
of the last occurrence in the file containing <nam>blah</nam>

So fails on this (returning 'wrong'):

<emp>
  <des>
    <nam>wanted</nam>
    <a>5</a>
  </des>
  <des>
    <nam>wrong</nam>
    <a>6</a>
  </des>
</emp>

 private static String parse(File f) throws IOException
     {
          int a = 0;
          String nam = null;
        BufferedReader in = new BufferedReader(new FileReader(f));
        String line = null;
        while (null!=(line = in.readLine()))
        {
             line = line.trim();
             if (line.equals("<a>5</a>"))
             {
                  a = 5;
             }
             else if (line.startsWith("<nam>"))
             {
                  nam = line.substring(5, line.indexOf("</nam>"));

             }
        }
        return a==5 ? nam : null;
     }
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> So fails on this (returning 'wrong'):

Thats why I asked earlier if the file was always in the same structure as posted :)
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now