0

So I've gotten help from here already so I figured why not try it out again!? Any suggestions would be greatly appreciated.

I'm using HTTP client and making a POST request; the response is an XML body that looks like the following:

<?xml version="1.0" encoding="UTF-8"?>
<CartLink 
    xmlns="http://api.gsicommerce.com/schema/ews/1.0">
    <Name>vSisFfYlAPwAAAE_CPBZ3qYh</Name>
    <Uri>carts/vSisFfYlAPwAAAE_CPBZ3qYh</Uri>
</CartLink>

Now...

I have an HttpEntity which is

[HttpResponse].getEntity(). 

Then I get a String representation of the response (which is XML in this case) by saying

String content = EntityUtils.toString(HttpEntity)

I tried following some of the suggestions on this post: How to create a XML object from String in Java? but it did not seem to work for me. When I built up the document it still appeared to be null.

MY END GOAL here is just to get the NAME field.. i.e. the "vSisFfYlAPwAAAE_CPBZ3qYh" part. So do I want to build up a document and then extract it...? Or is there a simpler way? I've been trying different things and I can't seem to get it to work.

Thanks for all of the help guys, it is most appreciated!!

Community
  • 1
  • 1
user2529603
  • 27
  • 3
  • 7

1 Answers1

1

Instead of trying to extract the value with string manipulation, try to use Java's inbuilt ability to parse XML. That's a much better approach. Http Components returns responses in an XML format - there's a reason for that. :)

Here's probably one way to solve your problem:

    // Parse the response using DocumentBuilder so you can get at elements easily
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(response);
    Element root = doc.getDocumentElement();
    // Now let's say you have not one, but 'n' nodes that contain the value
    // you're looking for. Use NodeList to get a list of all those nodes and just 
    // pull out the tag/attribute's value you want.
    NodeList nameNodesList = doc.getElementsByTagName("Name");
    ArrayList<String> nameValues = null;
    // Now iterate through the Nodelist to get the values you want.
    for (int i=0; i<nameNodesList.getLength(); i++){
         nameValues.add(nameNodesList.item(i).getTextContent());
    }

The ArrayList "nameValues" will now hold every single value contained within "Name" tags. You could also create a HashMap to store a key value pair of Nodes and their respective text contents.

Hope this helps.

Rubicon
  • 137
  • 7