java中的接口是类吗
393
2023-01-25
java 生成xml并转为字符串的方法
如下所示:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class test {
private String createXml() {
String xmlString = "";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.setXmlStandalone(true);
Element itemInfo = document.createElement("ItemInfo");
document.appendChild(itemInfo);
Element itemStatistics = document.createElement("ItemStatistics");
itemStatistics.setTextContent("商品统计");
itemInfo.appendChild(itemStatistics);
Element items = document.createElemenhttp://t("Items");
itemInfo.appendChild(items);
// 此处可以循环添加
Element item = document.createElement("Item");
items.appendChild(item);
Element itemName = document.createElement("ItemName");
itemName.setTextContent("iPhone");
item.appendChild(itemName);
Element itemNum = document.createElement("ItemNum");
itemNum.setTextContent("3");
item.appendChild(itemNum);
Element itemValue = document.createElement("ItemValue");
itemValue.setTextContent("1000000");
item.appendChild(itemValue);
Element remark = document.createElement("Remark");
remark.setTextContent("配送");
itemInfo.appendChild(redajBeUpFJmark);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource domSource = new DOMSource(document);
// xml transform String
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transformer.transform(domSource, new StreamResult(bos));
xmlString = bos.toString();
System.out.println(xmlString);
} catch (Exception e) {
e.printStackTrace();
}
return xmlString;
}
}
结果:
去掉头文件
的办法暂时只能想到:
xmlString.substring(38)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~