java and xml file

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>
pentiumnewbieAsked:
Who is Participating?
 
CEHJCommented:
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
 
CEHJCommented:
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
 
pentiumnewbieAuthor Commented:
When I say name I mean this value:

<nam>name</nam>

Thank you.
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
CEHJCommented:
You've lost me...
0
 
pentiumnewbieAuthor Commented:
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
 
pentiumnewbieAuthor Commented:
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
 
CEHJCommented:
So far, you are only looking at the first file - there's no loop
0
 
pentiumnewbieAuthor Commented:
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
 
objectsCommented:
> 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
 
CEHJCommented:
>>for(int cnt = 0; cnt < xmlFiles.length + 1; ++cnt){

should be

for(int cnt = 0; cnt < xmlFiles.length; cnt++){
0
 
CEHJCommented:
>>its *your* code :)

Please read the question thread before commenting

>>// read thus but in a loop with index 'i'
0
 
objectsCommented:
i did read the question, the comment didn't seem all that useful
and took more typing than the actual code :)
0
 
CEHJCommented:
>>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
 
pentiumnewbieAuthor Commented:

that worked,
for(int cnt = 0; cnt < xmlFiles.length; cnt++){
Will the last file be missed?
0
 
objectsCommented:
will all the xml files have the same structure?
0
 
objectsCommented:
> Will the last file be missed?

no
0
 
CEHJCommented:
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
 
CEHJCommented:
Whoops

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

should be *before* the loop
0
 
pentiumnewbieAuthor Commented:
>> 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
 
objectsCommented:
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
 
pentiumnewbieAuthor Commented:
>> will all the xml files have the same structure?
yes,

0
 
objectsCommented:
i'd use a different approach to your problem than has been posted, let me know if u are interested.
0
 
pentiumnewbieAuthor Commented:

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

Will this work?
str.valueOf(<nam>);
0
 
CEHJCommented:
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
 
CEHJCommented:
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
 
objectsCommented:
> 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
 
CEHJCommented:
>>str.valueOf(<nam>);

You need

String namValue = str.substring(str.indexOf("<nam>"), str.indexOf("</nam>"));
0
 
objectsCommented:
> 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
 
CEHJCommented:
Since you have small files you may as well read the whole file into a StringBuffer and then substring it after toString()
0
 
objectsCommented:
pentiumnewbie,

Is this all helping you?
0
 
pentiumnewbieAuthor Commented:
What could I add to the following to get the value?

String t = domNode.getNodeValue().trim();
0
 
objectsCommented:
Have you given up on CEHJ's suggested approach?
0
 
CEHJCommented:
if that node is 'a' then you can do

String namValue = domNode.getPreviousSibling().getNodeValue().trim();
0
 
objectsCommented:
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
 
pentiumnewbieAuthor Commented:

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
 
objectsCommented:
see the code I posted above, it provides a method to extract nam when a=5
0
 
pentiumnewbieAuthor Commented:
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
 
objectsCommented:
sorry for all the stuffing around :)
0
 
pentiumnewbieAuthor Commented:
No bother at all, i should do some of the work :)

Thanks again
0
 
CEHJCommented:
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
 
searlasCommented:
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
 
objectsCommented:
> So fails on this (returning 'wrong'):

Thats why I asked earlier if the file was always in the same structure as posted :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.