2011-10-03 66 views
0

我想用jdom創建一個Document對象。我寫了一個函數,但在調試後我可以看到它沒有被創建。由於我是XML新手,我不明白爲什麼我無法創建。你能幫我一下嗎?如何在Java中創建一個Document對象?

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); 
} 

當我嘗試轉換爲字符串以查看Document內部是什麼時,我得到;

<?xml version="1.0" encoding="UTF-8"?> 
<message /> 
+0

當您嘗試創建一個'Document'會發生什麼? 「不能創建」是什麼意思?你有例外嗎?如果是這樣,你能提供堆棧跟蹤嗎? –

+0

你是什麼意思,它不是'創造'?這個方法不會返回對象嗎? – Saket

+0

我編輯了我的問題。謝謝。 – Ozer

回答

3

從我所看到的,你創建了一個Document對象,並添加節點到headerbody節點,但這些節點沒有被添加到您的文檔對象實例document

我相信你會想要將這些節點添加到root元素,該元素已添加到您的document

所以,你可以如下圖所示將其添加到您的文檔的根:

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; 

} 
+0

非常感謝,它工作:) – Ozer

相關問題