你的位置:首页 > 软件开发 > Java > Dom4j中使用asXML方法之节点自闭和问题

Dom4j中使用asXML方法之节点自闭和问题

发布时间:2017-11-28 05:00:21
1 as  在使用Dom4j的时候,有时候需要将一个Document对象或Element对象转换为一个String,可以直接调用Document.as  其中:Element对象的element.as  但是,在使用这个法法的时候出现了以下问题:例如,我原始2 解决方案  自己封 ...

Dom4j中使用asXML方法之节点自闭和问题

1 as

  在使用Dom4j的时候,有时候需要将一个Document对象或Element对象转换为一个String,可以直接调用Document.as

  其中:Element对象的element.as

  但是,在使用这个法法的时候出现了以下问题:例如,我原始

2 解决方案

  自己封装as

 1 // 转换为标准格式(避免自闭合的问题) 2  private static String as 3   OutputFormat format = new OutputFormat(); 4   format.setEncoding("UTF-8"); 5   format.setExpandEmptyElements(true); 6   StringWriter out = new StringWriter(); 7   new  8   try { 9    writer.write(body);10    writer.flush();11   } catch (IOException e) {12    e.printStackTrace();13   }14   return out.toString();15  }

3 java代码示例

 1 package xin.dreaming.dom4j; 2  3 import java.io.IOException; 4 import java.io.StringWriter; 5  6 import org.dom4j.Document; 7 import org.dom4j.DocumentException; 8 import org.dom4j.DocumentHelper; 9 import org.dom4j.Element;10 import org.dom4j.io.OutputFormat;11 import org.dom4j.io.12 import org.junit.Test;13 14 public class Dom4jTest {15 16  @Test17  public void dom4jTest() throws DocumentException {18   String ;19   //原20   System.out.println(21   System.out.println("------------------------------------------------------------------------------");22   Document document = DocumentHelper.parseText(23   // 获取body节点24   Element body = document.getRootElement().element("BODY");25   //使用as26   System.out.println(body.as27   System.out.println("------------------------------------------------------------------------------");28   //使用自己封装的ax29   System.out.println(as30  }31 32  // 转换为标准格式(避免自闭合的问题)33  private static String as34   OutputFormat format = new OutputFormat();35   format.setEncoding("UTF-8");36   format.setExpandEmptyElements(true);37   StringWriter out = new StringWriter();38   new 39   try {40    writer.write(body);41    writer.flush();42   } catch (IOException e) {43    e.printStackTrace();44   }45   return out.toString();46  }47 }

输出结果:

<?

结果对比:

Dom4j中使用asXML方法之节点自闭和问题

 

原标题:Dom4j中使用asXML方法之节点自闭和问题

关键词:xml

xml
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。