使用Java解析SAX问题

时间:2011-06-27 18:23:09

标签: java xml sax xml-parsing directory

所以我之前问了一个问题,只是为了了解一些SAX的基础知识,我从答案中学到了很多东西。根据我的学习,我尝试创建一个Java程序,它将遍历一堆目录(我正在处理的大项目的必要部分),然后在目录中找到一个名为"document.xml.rels"的文件并使用SAX parser标识'Target'元素,查看它是否是图像文件(在其关联名称中包含“image”),然后将目标与Id属性相关联并执行system.out.print.我是没有从编译器或运行时获得任何错误,所以我想知道我是不是正确遍历目录结构还是在SaxHandler类中我的条件有问题?

只是一些笔记......

我开始在目录中:

C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Extracted Items

我正试图以文件结尾:

C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Extracted Items/ProposalOne/word/_rels/document.xml.rels

这是我的Java代码:

import java.io.*;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class XMLParser
{
    static File directory = new File("C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Extracted Items");
    static File files[] = directory.listFiles();

    public static void main(String[] args) throws IOException
    {
        //For each of the files in "/Extracted Items"...
        for(File f : files)
        {
            //...if it is a directory then...
            if(f.isDirectory())
            {
                //...create a new array populated with each of the files in the directory
                File directoryTwo = new File(f.getAbsolutePath());
                File filesTwo[] = directoryTwo.listFiles();

                //For each of the files in the new directory "/Proposal#"...
                for(File f2 : filesTwo)
                {
                    //...if it is a directory then...
                    if(f2.isDirectory())
                    {
                        //...create a new array populated with each of the files in the directory
                        File directoryThree = new File(f.getAbsolutePath());
                        File filesThree[] = directoryThree.listFiles();

                        //For each of the files in the new directory "/word"
                        for(File f3: filesThree)
                        {
                            //...if it is a directory then...
                            if(f3.isDirectory())
                            {
                                //...create a new array populated with each of the files in the directory
                                File directoryFour = new File(f.getAbsolutePath());
                                File filesFour[] = directoryFour.listFiles();

                                //For each of the files in the new directory "/_rels"
                                for(File f4: filesFour)
                                {
                                    if(f4.getName() == "document.xml.rels")
                                    {
                                        try 
                                        {
                                            // creates and returns new instance of SAX-implementation:
                                            SAXParserFactory factory = SAXParserFactory.newInstance();

                                            // create SAX-parser...
                                            SAXParser parser = factory.newSAXParser();

                                            // .. define our handler:
                                            SaxHandler handler = new SaxHandler();

                                            // and parse:
                                            parser.parse(f3.getAbsolutePath(), handler);    
                                        } 
                                        catch (Exception ex) 
                                        {
                                            ex.printStackTrace(System.out);
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

     private static final class SaxHandler extends DefaultHandler 
     {
         // invoked when document-parsing is started:
         public void startDocument() throws SAXException 
         {
             System.out.println("Document processing started");
         }

         // notifies about finish of parsing:
         public void endDocument() throws SAXException 
         {
             System.out.println("Document processing finished");
         }

         // we enter to element 'qName':
         public void startElement(String uri, String localName, 
                 String qName, Attributes attrs) throws SAXException 
         {
             if(localName.equals("Relationship"))
             {
                 if(attrs.equals("Target"))
                 {
                     if(attrs.getValue("Target").contains("image"))
                     {
                         String id = attrs.getValue("Id");
                         String target = attrs.getValue("Target");
                         System.out.println("Id: " + id + "& Target: " + target);
                     }
                 }
             }  
             else 
             {
                 throw new IllegalArgumentException("Element '" + 
                         qName + "' is not allowed here");
             }
         }

         // we leave element 'qName' without any actions:
         public void endElement(String uri, String localName, String qName)
         throws SAXException 
         {
                // do nothing;
         }
     }
}

以下是我正在使用的xml文档

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
      <Relationship Id="rId8" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml" /> 
      <Relationship Id="rId13" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml" /> 
      <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml" /> 
      <Relationship Id="rId7" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml" /> 
      <Relationship Id="rId12" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml" /> 
      <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml" /> 
      <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml" /> 
      <Relationship Id="rId6" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes" Target="endnotes.xml" /> 
      <Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image3.png" /> 
      <Relationship Id="rId5" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml" /> 
      <Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image2.jpeg" /> 
      <Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings" Target="webSettings.xml" /> 
      <Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/image1.jpeg" /> 
</Relationships>

新Java代码

import java.io.*;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class XMLParser
{   
    public static void main(String[] args) throws IOException
    {
        traverse(new File("C:/Documents and Settings/rajeeva/workspace/Intern Project/Proposals/Converted Proposals/Extracted Items"));
    }

     private static final class SaxHandler extends DefaultHandler 
     {
         // invoked when document-parsing is started:
         public void startDocument() throws SAXException 
         {
             System.out.println("Document processing started");
         }

         // notifies about finish of parsing:
         public void endDocument() throws SAXException 
         {
             System.out.println("Document processing finished");
         }

         // we enter to element 'qName':
         public void startElement(String uri, String localName, 
                 String qName, Attributes attrs) throws SAXException 
         {
             if(localName.equals("Relationship"))
             {
                 if(attrs.equals("Target"))
                 {
                     if(attrs.getValue("Target").contains("image"))
                     {
                         String id = attrs.getValue("Id");
                         String target = attrs.getValue("Target");
                         System.out.println("Id: " + id + "& Target: " + target);
                     }
                 }
             }  
             else 
             {
                 throw new IllegalArgumentException("Element '" + 
                         qName + "' is not allowed here");
             }
         }

         // we leave element 'qName' without any actions:
         public void endElement(String uri, String localName, String qName)
         throws SAXException 
         {
                // do nothing;
         }
     }

     private static void traverse(File directory)
     {
        //Get all files in directory
        File[] files = directory.listFiles();
        for (File file : files)
        {
           if (file.isDirectory())
           {
              //It's a directory so (recursively) traverse it
              traverse(file);
           }
           else if (file.getName().equals("document.xml.rels"))
           {
               try 
                {
                    System.out.println("5");
                    // creates and returns new instance of SAX-implementation:
                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    // create SAX-parser...
                    SAXParser parser = factory.newSAXParser();

                    // .. define our handler:
                    SaxHandler handler = new SaxHandler();

                    // and parse:
                    parser.parse(file.getAbsolutePath(), handler);    
                } 
                catch (Exception ex) 
                {
                    ex.printStackTrace(System.out);
                }
            }
         }
     }
}

新错误

Document processing started
java.lang.IllegalArgumentException: Element 'Relationships' is not allowed here
    at XMLParser$SaxHandler.startElement(XMLParser.java:48)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$ContentDriver.scanRootElementHook(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at XMLParser.traverse(XMLParser.java:87)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.main(XMLParser.java:13)
5
Document processing started
java.lang.IllegalArgumentException: Element 'Relationships' is not allowed here
    at XMLParser$SaxHandler.startElement(XMLParser.java:48)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$ContentDriver.scanRootElementHook(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at XMLParser.traverse(XMLParser.java:87)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.main(XMLParser.java:13)
5
Document processing started
java.lang.IllegalArgumentException: Element 'Relationships' is not allowed here
    at XMLParser$SaxHandler.startElement(XMLParser.java:48)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$ContentDriver.scanRootElementHook(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at XMLParser.traverse(XMLParser.java:87)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.main(XMLParser.java:13)
5
Document processing started
java.lang.IllegalArgumentException: Element 'Relationships' is not allowed here
    at XMLParser$SaxHandler.startElement(XMLParser.java:48)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$ContentDriver.scanRootElementHook(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at XMLParser.traverse(XMLParser.java:87)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.traverse(XMLParser.java:70)
    at XMLParser.main(XMLParser.java:13)

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

       if(f4.getName() == "document.xml.rels")

应该使用

       if(f4.getName().equals("document.xml.rels"))

编辑:重读代码我发现另一个问题。

             if(attrs.equals("Target"))

attrs的类型为Attributes,因此这种比较永远不会成立。

答案 1 :(得分:0)

您向我们显示的错误消息“此处不允许关系元素”表示该文档对其DTD无效。但是你还没有向我们展示DTD。

相关问题