0

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

    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>
4

1 回答 1

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);
}
于 2013-02-26T13:41:59.333 回答