Captain Spaulding
Captain Spaulding

Reputation: 33

Java: Loading and Displaying XML

I am trying to write a java program that reads in an XML file and returns various elements of interest to the user. I am having some issues getting it to compile and I have created a test class in order for it to be displayed properly. This is what I have thus far.

EDIT: The Bolded Line in the test class is giving me problems. The error is cannot convert from String to 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;

}

}

Upvotes: 2

Views: 164

Answers (3)

sjas
sjas

Reputation: 19677

The error lies in here:

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());

   ....

You pass a Resources Object, and normally you would want to work directly with it?
Currently this just seems borked here, all the other code works, I tested and get fancy console outputs.

EDIT: (Answering a comment below this post.)

In ResourceImporter.java add line following the comment below:

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");

            ....

You may also want to use this line for your syso's in the helper method being used in the main method: System.out.println(resources.getIdentifier().getURL());, otherwise you will get uninterpretable information.

Upvotes: 1

Matthieu
Matthieu

Reputation: 3097

I'd change

private static void displayResources(Resources resources)

to

private static void displayResources(Resources resource)

(notice I removed the 's'), and remove your bold line.

As stated by JB Nizet, your method returns a String when you want the Resources that is passed to your static method.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691755

The getTitle() method is declared as

public String getTitle()

But you're assigning its result to a variabe of type Resources:

Resources resource = resources.getTitle();

That obviously can't work, hence the error, which is quite self-explanatory:

cannot convert from String to Resources

You probably want

 String title = resources.getTitle();

instead.

Upvotes: 0

Related Questions