【发布时间】:2011-08-03 11:12:11
【问题描述】:
这可能是一个疯狂/愚蠢/愚蠢/冗长的问题,因为我是网络服务的新手。
我想编写一个 Web 服务,它将以 XML 格式返回答案(我正在使用我的服务进行 YUI 自动完成)。我正在使用 Eclipse 和 Axis2 并关注 http://www.softwareagility.gr/index.php?q=node/21
我想要以下格式的回复
<codes>
<code value="Pegfilgrastim"/>
<code value="Peggs"/>
<code value="Peggy"/>
<code value="Peginterferon alfa-2 b"/>
<code value="Pegram"/>
</codes>
code 元素的数量可能因响应而异。
到目前为止,我尝试了以下方法
1)使用字符串缓冲区创建 XML 并返回字符串。(我提供部分代码以避免混淆)
public String myService ()
{
// Some other stuff
StringBuffer outputXML = new StringBuffer();
outputXML.append("<?xml version='1.0' standalone='yes'?>");
outputXML.append("<codes>");
while(SOME_CONDITION)
{
// Some business logic
outputXML.append("<code value=\""+tempStr+"\">"+"</code>");
}
outputXML.append("</codes>");
return (outputXML.toString());
}
它使用不需要的<ns:myServiceResponse> 和<ns:return> 元素给出以下响应。
<ns:myServiceResponse>
<ns:return>
<?xml version='1.0' standalone='yes'?><codes><code value="Peg-shaped teeth"></code><code value="Pegaspargase"></code><code value="Pegfilgrastim"></code><code value="Peggs"></code><code value="Peggy"></code><code value="Peginterferon alfa-2 b"></code><code value="Pegram"></code></codes>
</ns:return>
</ns:findTermsResponse>
但它不适用于 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("<?xml version='1.0' standalone='yes'?>");
outputXML.append("<codes>");
while(SOME_CONDITION)
{
// Some business logic
outputXML.append("<code value=\"" + tempStr + "\">" + "</code>");
}
outputXML.append("</codes>");
out.println(outputXML.toString());
}
它给出了与上面提到的相同的响应,并且它与 YUI 自动完成一起工作,没有任何额外的标签。
请您告诉我如何在没有任何不需要的元素的情况下获得 XML 响应?
谢谢。
【问题讨论】:
标签: java web-services axis2