跳至内容

XML - 管理数据交换/分析 XML 文件/答疑

来自 Wikibooks,开放世界的开放书籍

This java class file is associated with the movies.xml file used in the 
chapter. Place this java file and movies.xml in the same directory. 
After compiling, this needs to be run from a command window and the format is:

> java SPParser movies.xml


import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import java.io.*;

public class SPParser
{

  static Document doc;


  public SPParser(String filename)
  {
    //filename S/B the name of the XML file to parse
    File file = new File(filename);
    try
    {

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      DocumentBuilder parser = factory.newDocumentBuilder();

      doc = parser.parse(file);

      System.out.println(file + " is well-formed.");
    }
    catch (SAXException e)
    {
      System.out.println( e.getMessage());
    }
    catch (IOException e)
    {
      System.out.println( e.getMessage());
    }
    catch (ParserConfigurationException e)
    {
      System.out.println("Could not locate a JAXP parser");
    }
  }


  public void readData(Node n)
  {
    System.out.println("Printing data and attributes");

    NamedNodeMap attributes = n.getAttributes();
    String strAttributes = "Production Company- '" + attributes.item(0).getNodeValue();

    if (attributes.getLength() == 2) //There are two attributes in the movies.xml file
      strAttributes += "' , Loaned To - '" + attributes.item(1).getNodeValue() + "' ,";
    else
      strAttributes += "' , Not out , ";

    NodeList values = n.getChildNodes();

    String dataString = "Movies Data:  " + strAttributes;
    int ancestor = 0;

    for (int i = 0; i < values.getLength(); i++)
    {
      Node child = values.item(i);

      if (child.getNodeType() != Node.TEXT_NODE)
      {
        String insert = child.getFirstChild().getNodeValue();

        if (insert.trim().length() != 0 && ancestor == 0)
        {
          dataString += "Movie Title - '"+insert+"', ";
          ancestor = 1;
        }
        else if (insert.trim().length() != 0  && ancestor == 1)
        {
          dataString += "Director - '"+insert+"'.";
          ancestor = 0;
        }
      }
    }//End of for-loop

    System.out.println(dataString);
    System.out.println();
  }//End of insertStatements()

  public static void main(String[] args)
  {
    SPParser p = new SPParser("movies.xml");

    NodeList n = doc.getElementsByTagName("movie");

    for (int i = 0; i < n.getLength(); i++)
    {
      p.readData(n.item(i));
    }
  }//End of main()

}//End of SPParser class
华夏公益教科书