Search code examples
androidandroid-ksoap2kxml2kxml

Parsing an XML string into a kXML Element


I'm writing an Android app that connects to a SOAP webservice using kSOAP2, and I have a kXML element where I would like to inject a child based on an XML string I got from elsewhere (a REST API). I have the following code:

Element samlHeader = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
samlHeader.setPrefix("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
samlHeader.setPrefix("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

String samlTokenString = ...; //I got this from elsewhere
Element samlTokenElement = ...; //I don't know how to build this
samlHeader.addChild(Node.ELEMENT, samlTokenElement);

So I'm trying to figure out how to build my Element based on the XML string I'm getting from elsewhere.


Solution

  • This is the solution that we ended up implementing:

    try {
        KXmlParser parser = new KXmlParser();
        parser.setInput(new StringReader(samlTokenString));
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    
        Document samlTokenDocument = new Document();
        samlTokenDocument.parse(parser);
        samlHeader.addChild(Node.ELEMENT, samlTokenDocument.getRootElement());
    } catch (XmlPullParserException e) {
        Log.e(TAG,"Could not parse SAML assertion", e);
    } catch (IOException e) {
        Log.e(TAG,"Could not parse SAML assertion", e);
    }
    

    We're still validating if it produces the right result but it seems to work.