Parsing a RESTful XML response and displaying in JTable

My web service is working and I can print out the XML retrieved by the Service with my code below:

resource = client.resource("http://localhost:8080/testProject/rest/items");
ClientResponse response= resource.get(ClientResponse.class);
String entity = response.getEntity(String.class);

However I'm trying to now use this XML to be the data provider for a JTable, and I can't work out how to parse it. My code is below but won't work because "entity" is a string.

    JAXBContext context = JAXBContext.newInstance(Item.class);
    Unmarshaller um = context.createUnmarshaller();
    Item item = (Item) um.unmarshal(entity);

So my question(s) are

What am I doing wrong here?

Should I not be using .getEntity(String.Class) to do this?

Is there an easier way to get this XML response into a JTable?



first, don't convert xml to String data unless absolutely necessary (it's fine for debug output, but not for real work). i haven't used jersey personally, but i'd imagine you can get the xml in a better form than a String (e.g. a DOM Document).

however, if you must get the xml from a string, then you can unmarshal it like so:

um.unmarshal(new StringReader(entity));

You can create a Document from your String using a method like that:

 public static Document loadXML(String xmlAsString) {
    DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xmlAsString));
    return b.parse(is);

Then you can use that Document and get the data you need to populate your JTable.

Read the response as a Document

Document xml = wsResponse.asXml();

Use below code snippet after that for text conversion I used the ref

void displayXml(Document doc) {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {
        transformer = tf.newTransformer();
    } catch (TransformerConfigurationException e1) {
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    try {
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
    } catch (TransformerException e) {
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

Need Your Help

Android 4.3 menu item showAsAction="always" ignored

android menuitem android-support-library android-actionbar-compat

I'm using the new v7 appcompat library available starting from Android 4.3 (API level 18).