0

for XML File parsing I am using JAXB but after compilation following error is reported

javax.xml.bind.JAXBException: No package name is given
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at searchAlgo.Question.<init>(Question.java:16)

code is given below

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class Question {
//String question = new String() ;
String s = new String();
Question()
{
    try{
        File file = new File("C:\\Users\\Username\\Documents\\levels.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(s); 

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        String string = (String) jaxbUnmarshaller.unmarshal(file);

        System.out.println(string);


    }
    catch(JAXBException e){
        e.printStackTrace();
    }
}}

do I need to install JAXB plug-in? i am using jdk 1.8.0_91 and eclipse mars

user007
  • 88
  • 1
  • 9
  • This question has been asked before. https://stackoverflow.com/questions/20273355/why-does-jaxbcontext-need-to-be-told-specifically-about-a-class-that-is-already – user8271644 Jul 18 '17 at 15:07

2 Answers2

1

JAXBContext.newInstance() expects either a Class or a package name. Since s is a String, it is interpreted as a package name. But your String is empty, so you get "No package name is given"

1

Your problem is that you're not using JAXB correctly.

First,

JAXBContext jaxbContext = JAXBContext.newInstance(s);

is wrong because JAXBContext.newInstance(...) is expecting either a class or " separated java package names that contain schema-derived classes and/or fully qualified JAXB-annotated classes" according to documentation

The point is to determine what kind of objects JAXB is dealing with. In other words, it will be what kind of objects you have inside C:\\Users\\Username\\Documents\\levels.xml XML file.

Second,

if you want to unmarshall objects from XML file or marshall objects to String, I suggest you read the following documentation with a lot of examples:

Mickael
  • 4,458
  • 2
  • 28
  • 40