How to create a Document object in Java?
I want to create a Document object with jdom. I have written a function but after I debug I can see that it is not created. and since I am new to XML I don't understand why I can not create. Can you please help me for that?
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;
}
When I create it, I convert it to string by using that function ;
public String xmlToString(Document doc) {
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
return outputter.outputString(doc);
}
and When I try to convert to string to see what is inside of the Document, i get;
<?xml version="1.0" encoding="UTF-8"?>
<message />
From what I can see, you are creating a Document object, and adding nodes to the header
and body
nodes, but these nodes are not being added to your Document object instance document
.
I believe you would want to add these nodes to the root
element, which is already added to your document
.
So, you could add it to your document's root as shown below:
public Document createSNMPMessage (){
Element root = new Element("message");
Document document = new Document(root);
Element header = new Element("header");
...
...
Element body = new Element("body");
...
...
root.addContent(header); // NOTE THESE NEW LINES
root.addContent(body); // NOTE THESE NEW LINES
return document;
}
精彩评论