因为别人的接口要求是Xml文件。并且有很多自定义标签。
并且要求不能自闭合。
UserInfoimport lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class UserInfo { private String username; private String password; }生成XmlUtil
import java.io.File; import java.lang.reflect.Field; import javax.xml.parsers.documentBuilder; import javax.xml.parsers.documentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.document; import org.w3c.dom.Element; public class DomXmlUtil { public static void main(String[] args) { Long start = System.currentTimeMillis(); createXml(); System.out.println("运行时间:" + (System.currentTimeMillis() - start)); } public static Element buildXml(String one, Object dataItem, document document) throws Exception { Element header = document.createElement(one); //如果为空就返回一级 if (null == dataItem) { return header; } Field[] fields = dataItem.getClass().getDeclaredFields(); for (Field field : fields) { //设置是否允许访问,不是修改原来的访问权限修饰词。 field.setAccessible(true); Element element = document.createElement(field.getName().toUpperCase()); //根据字段名 element.setTextContent(String.valueOf(field.get(dataItem))); header.appendChild(element); } return header; } public static void createXml() { try { // 创建解析器工厂 documentBuilderFactory factory = documentBuilderFactory.newInstance(); documentBuilder db = factory.newdocumentBuilder(); document document = db.newdocument(); document.setXmlStandalone(true); Element root = document.createElement("ROOT"); UserInfo userInfo = new UserInfo(); userInfo.setUsername("韩一聪"); userInfo.setPassword("1111"); Element data = buildXml("DATA", userInfo, document); root.appendChild(data); document.appendChild(root); // 创建TransformerFactory对象 TransformerFactory tff = TransformerFactory.newInstance(); // 创建 Transformer对象 Transformer tf = tff.newTransformer(); // 输出内容是否使用换行 tf.setOutputProperty(OutputKeys.INDENT, "yes"); // 创建xml文件并写入内容 tf.transform(new DOMSource(document), new StreamResult(new File("test.xml"))); System.out.println("生成test.xml成功"); } catch (Exception e) { e.printStackTrace(); System.out.println("生成test.xml失败"); } } }输出结果 解决自闭合问题 因为这里用的是org.w3c.dom.document,没有找到这个解决自闭合的方法。所以把org.w3c.dom.document强转为org.dom4j.document 并且我需要获取Data中的数据并且返回字符串
private static String colseQuestion(org.w3c.dom.document w3cDoc) { org.dom4j.io.DOMReader reader = new DOMReader(); org.dom4j.document document = reader.read(w3cDoc); //获取DATA org.dom4j.Element data = document.getRootElement().element("DATA"); OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); format.setExpandEmptyElements(true); StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, format); try { writer.write(data); writer.flush(); } catch (IOException e) { e.printStackTrace(); } return out.toString(); }输出结果对比
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)