Solved

java and xml file

Posted on 2004-04-25
42
285 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
ID: 10913955
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
ID: 10913957
When I say name I mean this value:

<nam>name</nam>

Thank you.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10913982
You've lost me...
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:pentiumnewbie
ID: 10914041
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
ID: 10914121
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
ID: 10914130
So far, you are only looking at the first file - there's no loop
0
 

Author Comment

by:pentiumnewbie
ID: 10914163
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
ID: 10914170
> 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
ID: 10914171
>>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
ID: 10914177
>>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
ID: 10914184
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
ID: 10914201
>>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
ID: 10914204

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

Expert Comment

by:objects
ID: 10914207
will all the xml files have the same structure?
0
 
LVL 92

Expert Comment

by:objects
ID: 10914212
> Will the last file be missed?

no
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10914214
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
ID: 10914219
Whoops

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

should be *before* the loop
0
 

Author Comment

by:pentiumnewbie
ID: 10914237
>> 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
ID: 10914240
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
ID: 10914253
>> will all the xml files have the same structure?
yes,

0
 
LVL 92

Expert Comment

by:objects
ID: 10914265
i'd use a different approach to your problem than has been posted, let me know if u are interested.
0
 

Author Comment

by:pentiumnewbie
ID: 10914268

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

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

Expert Comment

by:CEHJ
ID: 10914273
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
ID: 10914279
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
ID: 10914280
> 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
ID: 10914286
>>str.valueOf(<nam>);

You need

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

Expert Comment

by:objects
ID: 10914291
> 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
ID: 10914311
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
ID: 10914313
pentiumnewbie,

Is this all helping you?
0
 

Author Comment

by:pentiumnewbie
ID: 10914330
What could I add to the following to get the value?

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

Expert Comment

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

Expert Comment

by:CEHJ
ID: 10914337
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
ID: 10914342
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
ID: 10914399
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
ID: 10914560

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
ID: 10914578
see the code I posted above, it provides a method to extract nam when a=5
0
 

Author Comment

by:pentiumnewbie
ID: 10914654
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
ID: 10914671
sorry for all the stuffing around :)
0
 

Author Comment

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

Thanks again
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10917234
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
ID: 10919951
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
ID: 10922952
> 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Weekend adv creator 3 54
factorial example 4 50
web application structure 18 102
hibernate example issues from command prompt 10 50
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

820 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