Java:加载和显示XML

时间:2013-07-27 19:46:48

标签: java

我正在尝试编写一个读取XML文件的java程序,并返回用户感兴趣的各种元素。我有一些问题需要编译,我已经创建了一个测试类,以便正确显示它。这是我迄今为止所拥有的。

编辑:测试课中的粗线让我有问题。该错误无法从String转换为Resources。

public class T_Resources {

public static void main(String[] args) {

    Resources resources = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");

    displayResources(resources);

}

private static void displayResources(Resources resources) {

    Subject[] subjects;

    **Resources resource = resources.getTitle();**

    System.out.println(resource.getTitle());

    System.out.println(resource.getDescription());

    System.out.println(resource.getIdentifier());

    subjects = resource.getSubjects();

    for (int i=0; i < subjects.length; ++i) {

        System.out.println(subjects[i].getCategory() + " :: " + subjects[i].getSubcategory());

    }

    System.out.println();
}

}

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class ResourceImporter {

// This operation loads the XML document specified by the document location, which     can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {

    // The XML document.
    //
    Document documentIn     = null;

    // The parser that reads in an XML files.
    //
    DocumentBuilder parser  = null;

    // Pull the document
    //
    try {

        // Obtain a document parser.
        //
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        builderFactory.setNamespaceAware(true);

        parser = builderFactory.newDocumentBuilder();

        documentIn = parser.parse(documentLocation);

    } catch (ParserConfigurationException p) {

        System.out.println("Error creating parser.");
        System.out.println("   " + p.getMessage());

    } catch (SAXException s) {

        System.out.println("Document is not well formed.");
        System.out.println("   " + s.getMessage());

    } catch (IOException i) {

        System.out.println("Error accessing the file.");
        System.out.println("   " + i.getMessage());

    } catch (Exception e) {

        System.out.println("Unknown error occurred.");
        System.out.println("   " + e.getMessage());

    }


    return documentIn;

}

public static Resources importResourcesFromXML(String documentLocation) { 

    Resources resource = new Resources();

    Document doc;

    Element resourceElement;

    Element titleElement;
    String title;

    Element descriptionElement;
    String description;

    Element identifierElement;
    String identifiers;

    Element urlElement;
    String url;

    NodeList subjectList;

    Element subjectElement;
    String subjects;

    Element categoryElement;
    String category;

    Element subcategoryElement;
    String subcategory;


    doc = loadXMLDocument(documentLocation);

    resourceElement = (Element)doc.getElementsByTagName("resource").item(0);


    if (resourceElement != null) {

        titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);  

        resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );

        descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);

        resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );

        identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);


        if (identifierElement != null) {

            Identifier identifier = new Identifier();

            urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);

            identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );

            subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);

            if (subjectElement != null) {

                subjectList =     subjectElement.getElementsByTagName("subject");

                for (int i=0; i < subjectList.getLength(); ++i) {

                    Subject subject = new Subject();

                    subjectElement = (Element)subjectList.item(i);

                    categoryElement =     (Element)subjectElement.getElementsByTagName("category").item(0);

                    subject.setCategory( categoryElement == null ?     "unknown"  : categoryElement.getTextContent() );

                    subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);

                    subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );

                    resource.addSubject(subject);

                }
            }

        }
    }

    return resource;

}

}


public class Resources {

private static final int    MAX_SUBJECTS = 20;
private String              title;  
private String              description;
private Identifier          identifier;
private Subject[]           subjects;
private int                 subjectCount;


public Resources() {

    title           = "unknown title";
    description     = "unknown description";
    identifier      = null;

    subjects        = new Subject[MAX_SUBJECTS];
    subjectCount    = 0;

}

public void setTitle(String newTitle) {

    title = newTitle;

}

public String getTitle() {

    return title;

}

public void setDescription(String newDescription) {

    description = newDescription;

}

public String getDescription() {

    return description;

}

public void setIdentifier(Identifier newIdentifier) {

    identifier = newIdentifier;

}

public Identifier getIdentifier() {

    return identifier;

}

public void addSubject(Subject newSubject) {

    subjects[subjectCount++] = newSubject;

}

public Subject[] getSubjects() {

    Subject[] result = new Subject[subjectCount];

    System.arraycopy(subjects, 0, result, 0, subjectCount);

    return result;
}

}



public class Subject {

private String category;
private String subcategory;

public Subject() {

    String category         = "unknown";
    String subcategory      = "unknown";

}

public Subject(Subject subject) {

    category        = subject.category;
    subcategory     = subject.subcategory;

}

public void setCategory(String newCategory) {

    category = (newCategory == null) ? "unknown" : newCategory;

}

public String getCategory() {

    return category;

}

public void setSubcategory(String newSubcategory) {

    subcategory = newSubcategory;

}

public String getSubcategory() {

    return subcategory;

}
}


public class Identifier {

private String url;

public Identifier() {

    url = "unknown";

}

public void setURL(String newURL) {

    url = newURL;

}

public String getURL() {

    return url;

}

}

3 个答案:

答案 0 :(得分:1)

错误在于:

private static void displayResources(Resources resources) {

    Subject[] subjects;

    // DELETE THIS
    // **Resources resource = resources.getTitle();**


    // RENAME 'resource' to 'resources', or just change the method parameter above...
    System.out.println(resources.getTitle());
    //System.out.println(resource.getTitle());

    System.out.println(resources.getDescription());
    //System.out.println(resource.getDescription());

    System.out.println(resources.getIdentifier());
    //System.out.println(resource.getIdentifier());

   ....

您传递了一个资源对象,通常您希望直接使用它?
目前这看起来似乎只是在这里,所有其他代码都可以工作,我测试并获得了奇特的控制台输出。

编辑:(在这篇文章下面回答评论。)

在以下评论后的ResourceImporter.java添加行中:

if (resourceElement != null) {

        titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);  

        resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );

        descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);

        resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );

        identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);


        if (identifierElement != null) {

            Identifier identifier = new Identifier();

            urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);

            identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );

            // ADDED THIS LINE HERE
            resource.setIdentifier(identifier);

            subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);

            if (subjectElement != null) {

                subjectList =     subjectElement.getElementsByTagName("subject");

            ....

您可能还希望在主方法中使用的辅助方法中使用此行作为syso:System.out.println(resources.getIdentifier().getURL());,否则您将获得无法解释的信息。

答案 1 :(得分:1)

我要改变

private static void displayResources(Resources resources)

private static void displayResources(Resources resource)

(注意我删除了's'),并删除粗线。

如JB Nizet所述,当您需要传递给静态方法的资源时,您的方法返回一个String。

答案 2 :(得分:0)

getTitle()方法声明为

public String getTitle()

但是您将其结果分配给类型为Resources的变量:

Resources resource = resources.getTitle();

这显然不起作用,因此错误,这是非常不言自明的:

  

无法从String转换为资源

你可能想要

 String title = resources.getTitle();

代替。