如何从Web服务返回XML
这可能是疯狂/愚蠢/愚蠢/冗长的问题之一,因为我是网络服务的新手。
我想写一个Web服务,它将以XML格式返回答案(我正在使用我的服务进行YUI自动完成)。 我正在使用Eclipse和Axis2并关注http://www.softwareagility.gr/index.php?q=node/21我希望以下列格式回复
code
元素的数量可能因响应而异。 直到现在我尝试了以下方法
1)使用String缓冲区创建XML并返回字符串。 (我提供部分代码以避免混淆)
public String myService () { // Some other stuff StringBuffer outputXML = new StringBuffer(); outputXML.append(""); outputXML.append(""); while(SOME_CONDITION) { // Some business logic outputXML.append(""+"
"); } outputXML.append(""); return (outputXML.toString()); }
它使用不需要的和
元素提供以下响应。
但它没有使用YUI自动完成(可能是因为它需要上面提到的格式的响应)
2)使用DocumentBuilderFactory :
喜欢
public Element myService () { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element codes = doc.createElement("codes"); while(SOME_CONDITION) { // Some business logic Element code = doc.createElement("code"); code.setAttribute("value", tempStr); codes.appendChild(code); } return(codes); }
得到以下错误
org.apache.axis2.AxisFault: Mapping qname not fond for the package: com.sun.org.apache.xerces.internal.dom
3)使用servlet:我尝试使用简单的servlet获得相同的响应,并且它有效。 这是我的servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer outputXML = new StringBuffer(); response.setContentType("text/xml"); PrintWriter out = response.getWriter(); outputXML.append(""); outputXML.append(""); while(SOME_CONDITION) { // Some business logic outputXML.append("" + "
"); } outputXML.append(""); out.println(outputXML.toString()); }
它给出了与上面提到的相同的响应,它与YUI自动完成一起工作,没有任何额外的标记。
请问您能告诉我如何在没有任何不需要的元素的情况下获得XML响应?
谢谢。
Axis2用于将对象传递回调用者。 这就是为什么它为响应添加额外的东西,即使它是一个简单的String对象。
使用第二种方法,您的服务返回一个用于描述XML片段的复杂Java对象( Element
实例)。 这样调用者必须知道该对象能够对其进行反序列化并恢复包含XML数据的Java对象。
第三种方法是关于返回类型的最简单和最好的方法:它不返回序列化的Java对象,只返回纯xml文本。 当然你可以使用DocumentBuilder
来准备XML,但最后你必须通过调用相应的getXml()
, asXml()
方法(或者……的类型asXml()
来创建它的String。
最后让它工作,虽然我无法删除不需要的元素。 (在所有事情都到位之前我都不打扰)。 我使用AXIOM来生成响应。
public OMElement myService () { OMFactory fac = OMAbstractFactory.getOMFactory(); OMNamespace omNs = fac.createOMNamespace("", ""); OMElement codes = fac.createOMElement("codes", omNs); while(SOME_CONDITION) { OMElement code = fac.createOMElement("code", null, codes); OMAttribute value = fac.createOMAttribute("value", null, tempStr); code.addAttribute(value); } return(codes); }
链接:1) http://songcuulong.com/public/html/webservice/create_ws.html
2) http://sv.tomicom.ac.jp/~koba/axis2-1.3/docs/xdocs/1_3/rest-ws.html
我想你不能用Axis返回你的自定义xml。 无论如何它会把它包裹在信封里。