Java webservice从dom中删除cdata

时间:2013-02-26 07:49:38

标签: java xml dom

我的Web服务返回一个字符串(xml)am使用DOM构建此字符串现在问题是当我想将此xml转换为String时。最初添加了一个额外的CDATA,我似乎无法将其删除。 我从stackoverflow得到了这个漂亮的函数,但提到的问题是它添加了我不需要的CDATA,因为我想返回一个Xml字符串。 请注意,我没有使用Soap网络服务。

    public static String doctoString(Document doc) {
    try {
        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Error converting to String", ex);
    }
}

完整输出:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:getInvoppResponse xmlns:ns2="http://services.com/">
         <return>
           <![CDATA[
              <users>
                 <user>
                    <id>1</id>
                    <name>sert</name>
                 </user>
              </users>
            ]]>
          </return>
      </ns2:getInvoppResponse>
   </soap:Body>
</soap:Envelope>

需要身体输出:

           <return>           
             <users>
               <user>
                  <id>1</id>
                  <name>sert</name>
               </user>
             </users>             
           </return>

1 个答案:

答案 0 :(得分:0)

对于不太优雅但功能强大的Java解决方案(针对新XML进行了更新):

p = Pattern.compile("\\A.*?(\\<users\\>.*\\<\\/users\\>).*?\\z", Pattern.DOTALL );
s = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
"   <soap:Body>\n" +
"     <ns2:getInvoppResponse xmlns:ns2=\"http://services.com/\">\n" +
"      <return>\n" +
"        <![CDATA[\n" +
"           <users>\n" +
"              <user>\n" +
"                 <id>1</id>\n" +
"                 <name>sert</name>\n" +
"              </user>\n" +
"           </users>\n" +
"         ]]>\n" +
"       </return>\n" +
"    </ns2:getInvoppResponse>\n" +
"    </soap:Body>\n" +
"</soap:Envelope>\n";

Matcher m = p.matcher(s);
if (m.matches())
{
    s =m.group(1);
}