问题
In a notification Worklight adapter - I invoke the adapter passing a very long XML string from the backend service.
The backend service cannot be altered or changed.
I want to be able to turn the javascript String object into something I can parse and use useful functions on such as :
var custNum = doc.getElementsByTagName("data:custNum")[0];
However all attempts so far at creating the 'doc' variable have failed. Standard DOMParser and window methods are undefined and out of scope in adapters. I would rather not resort to lengthy string splitting to find my nodes!
Many thanks
回答1:
Set returnedContentType: "xml". This will force WL platform to parse XML for you automatically and convert it to JSON you can manipulate.
E.g.
<a>
<b>
c
</b>
</a>
Will be converted to
{"a":
{"b":"c"}
}
so you can get values with syntax like response.a.b
回答2:
You should use XSL Transformation Filtering to get rid of all unneeded data from the XML.
Something like this should be your adapter JavaScript function:
function getFeedsFiltered() {
var input = {
method : 'get',
returnedContentType : 'xml',
path : "rss.xml",
transformation : {
type : 'xslFile',
xslFile : 'filtered.xsl'
}
};
return WL.Server.invokeHttp(input);
}
and something like this should be in your XSL file
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:dc="http://purl.org/dc/elements/1.1/" >
<xsl:output method="text"/>
<xsl:template match="/">
{
'Items': [
<xsl:for-each select="//item">
{
'title': '<xsl:value-of select="title"/>',
'creator': '<xsl:value-of select="dc:creator"/>',
'link': '<xsl:value-of select="link"/>',
'pubDate': '<xsl:value-of select="pubDate"/>'
},
</xsl:for-each>
]
}
</xsl:template>
</xsl:stylesheet>
Please check Getting started with IBM Worklight (http://www.ibm.com/developerworks/mobile/worklight/getting-started.html) module 5.2 - Creating HTTP Adapters(ftp://public.dhe.ibm.com/software/mobile-solutions/worklight/docs/v505/Module_05_2_-_Creating_HTTP_Adapters.pdf) and its exercise and code sample(ftp://public.dhe.ibm.com/software/mobile-solutions/worklight/docs/v505/module_05_2_HTTP_Adapter.zip).
回答3:
In the end I wrote a function like this :
function findNode(node,string){
var nodeEnd = node.slice(0, 1) + "/" + node.slice(1);
var chunk = string.split(node)[1];
var chunk2 = chunk.split(nodeEnd)[0];
return chunk2;
}
Which I use - nice and simple.
来源:https://stackoverflow.com/questions/15350362/what-is-the-way-to-parse-xml-in-a-worklight-adapter