0

I'm currently writing a text processing program in Java that needs to pull XML from an XML file and convert that into a Java object. I'm using what the quick tutorial on the XStream website suggested:

    XStream xstream = new XStream();
    Map<String, Integer> englishCorpusProbDist = (Map<String, Integer>)xstream.fromXML(xmlString);

where "xmlString" is the XML code. The only problem is that I have the XML in an XML file saved elsewhere on my computer, rather than as a string in my program. Is there a way to feed in the local address of the XML file into the .fromXML function and have it read the XML in the file, rather than directly feeding the XML itself into the function?

Any help would be much appreciated. Thanks in advance!

user3246779
  • 125
  • 3
  • 12

3 Answers3

0

Check out the other posts on Stackoverflow on how to read the contents from a file into a String with Java, e.g. this article.

Or you use the XStream.fromXML(File file) method, i.e.

XStream.fromXML(new File("myfile.xml"));
Community
  • 1
  • 1
Ralf Wagner
  • 1,467
  • 11
  • 19
0

You just have to look for how you can create a Java String object from xml file, which you can pass to fromXML() method. Refer this link for more reference on SO, for how to create String from XML document.

Community
  • 1
  • 1
Mandar Pandit
  • 2,171
  • 5
  • 36
  • 58
0

Try this working example

public class Person {
    private String firstname;
    private String lastname;

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }   
}

And execute the below code

public static void main(String[] args) throws Exception{
    XStream xstream = new XStream();    
    Person person = (Person)xstream.fromXML(new FileReader("a.xml"));
    System.out.println(person.getFirstname());
}
prashant thakre
  • 5,061
  • 3
  • 26
  • 39