-1

I am trying to parse the following XML.

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <GetTokenResponse xmlns="http://www.xx.co.uk/Services/Sourcing/xx">
         <GetTokenResult><?xml version="1.0" encoding="utf-8"?><GetTokenResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.xxx.co.uk/Services/xx"><Version /><Header><CorrelationID xmlns="" /><ResponseEndPoint xmlns="" /><ResponseType xmlns="">Response</ResponseType></Header><Errors /><Data><Response><Version xmlns="" /><Token xmlns="">CK-RUWelME68FGRJ3IpSf8MJ2T9XUazdJy-ll3uRzKc</Token><AccessStatus xmlns="">Granted</AccessStatus></Response></Data></GetTokenResponse>></GetTokenResult>
      </GetTokenResponse>
   </soap:Body>
</soap:Envelope>

I have tried parsing it using XmlStreamReader and Doc.Document but as soon as I hit the internal xml document (string inside <GetTokenResult> tag), it's unable to parse it.

2
  • 1
    Please edit the question to add the exact error message or behaviour you see.
    – Phil W
    Commented Apr 15, 2022 at 6:49
  • 1
    There are two </GetTokenResponse> tags in your code. Commented Apr 18, 2022 at 23:00

1 Answer 1

0

If you want to extract the Token alone, you could use a REGEX as opposed to using an XML Parser:

public static final String TOKEN_STRUCTURE = '<Token.*>(.*)</Token>';

public static void extractToken(String xml) {
  Matcher tokenMatcher = Pattern.compile(TOKEN_STRUCTURE).matcher(xml);
  Boolean hasMatches = tokenMatcher.find();

  if(hasMatches) {
    return tokenMatcher.group(1);
  }

  return null;
}
1
  • XML is a context-free language, which is "more powerful" than a regular language. Regex (Regular Expressions) work on regular languages, so regex is not a good tool for working with XML. It may work in limited cases. Extracting the nested <GetTokenResponse>, for example, would be difficult (if it's possible at all).
    – Derek F
    Commented Apr 19, 2022 at 23:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .