0

Possibly a quite simple question. I have a Element from a XML request and I have done:

Element number;

number = serviceDetail.getChild("Number");

I now want to convert the Element number into a String and then be able to use the substring function on it. What is the most effective way to transform a element into a string? toString() failed and the string prints like @a06816 and trying to transform it seemed to throw alot of errors.

Any help will be appreciated

Edit: Sorry I wasn't 100% clear. The contents of the number element will be the value that is inside the 'Number' element in the XML request which will be a string.

SOLVED: Instead of the above code I used:

String number;
number = serviceDetail.getChildText("Number");

Oops sorry for the hassle guys!

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Sad
  • 148
  • 1
  • 3
  • 13
  • 1
    What do you want the contents of the string to be? – Jon Skeet Jul 26 '11 at 13:40
  • Obtain the content of the element first before trying to convert it to string. What you're doing now is converting the child element (object) to string not the value. – Bitmap Jul 26 '11 at 13:43
  • possible dup of [632043](http://stackoverflow.com/questions/632043/how-do-i-extract-child-element-from-xml-to-a-string-in-java). See transformer. – alphazero Jul 26 '11 at 13:44

2 Answers2

0

I believe what you are trying to do requires you to marshall the element to your desired destination. If you use JAXB, you can do it like this: (taken from http://ws.apache.org/jaxme/manual/ch02s02.html)

public String asString(JAXBContext pContext, Object pObject) throws JAXBException {

    java.io.StringWriter sw = new StringWriter();

    Marshaller marshaller = pContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.marshal(pObject, sw);

    return sw.toString();
}

I -believe- pObject can be an org.w3c.dom.Element (assuming thats the Element class you are using.)

Hope that helps, Nick

Nick
  • 8,181
  • 4
  • 38
  • 63
  • I just noticed the link I posted was for jaxme...oops. But I think the approach for JAXB is identical, or at least similar enough. Getting a JAXBContext however can be a subject unto it's self. – Nick Jul 26 '11 at 13:54
0

Instead of the above code I used:

String number; number = serviceDetail.getChildText("Number");

Oops sorry for the hassle guys!

Sad
  • 148
  • 1
  • 3
  • 13