我想用 jdom 创建一个 Document 对象。我已经编写了一个函数,但是在调试之后我可以看到它没有被创建。由于我是 XML 新手,我不明白为什么我不能创建。你能帮我吗?
public Document createSNMPMessage (){
Element root = new Element("message");
Document document = new Document(root);
Element header = new Element("header");
Element messageType = new Element("messageType").setText("snmp");
Element sendFrom = new Element("sendFrom").setText("192.168.0.16");
Element hostName = new Element("hostName").setText("oghmasysMehmet");
Element sendTo = new Element("sendTo").setText("192.168.0.12");
Element receiverName = new Element("receiverName").setText("Mehmet");
Element date = new Element("date").setText("03/10/2011");
header.addContent(messageType);
header.addContent(sendFrom);
header.addContent(hostName);
header.addContent(sendTo);
header.addContent(receiverName);
header.addContent(date);
Element body = new Element("body");
Element snmpType = new Element("snmpType").setText("getbulk");
Element ip = new Element("ip").setText("127.0.0.1");
Element port = new Element("port").setText("161");
Element oids = new Element("oids");
Element oid = new Element("oid").setText("1.3.6.1.2.1.1.3.0");
oids.addContent(oid);
Element community = new Element("community").setText("community");
Element nR = new Element("nR").setText("0");
Element mR = new Element("mR").setText("5");
body.addContent(snmpType);
body.addContent(ip);
body.addContent(port);
body.addContent(oids);
body.addContent(community);
body.addContent(nR);
body.addContent(mR);
return document;
}
创建它时,我使用该函数将其转换为字符串;
public String xmlToString(Document doc) {
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
return outputter.outputString(doc);
}
当我尝试转换为字符串以查看文档内部的内容时,我得到了;
<?xml version="1.0" encoding="UTF-8"?>
<message />