2013-03-05 112 views
8

如何將具有XML格式內容的字符串轉換爲JDom文檔。如何將包含XML格式內容的字符串轉換爲JDom文檔

我與下面的代碼嘗試:

String docString = txtEditor.getDocumentProvider().getDocument(
txtEditor.getEditorInput()).get(); 

SAXBuilder sb= new SAXBuilder(); 

doc = sb.build(new StringReader(docString)); 

任何一個可以幫助我解決上述問題。 在此先感謝!

回答

11

這是你一般是如何解析的XML文檔

try { 
    SAXBuilder builder = new SAXBuilder(); 
    Document anotherDocument = builder.build(new File("/some/directory/sample.xml")); 
} catch(JDOMException e) { 
    e.printStackTrace(); 
} catch(NullPointerException e) { 
    e.printStackTrace(); 
} 

這是從JDOM IBM Reference

如果採取你的字符串,你可以將其轉換爲InputStream,然後將它傳遞

String exampleXML = "<your-xml-string>"; 
InputStream stream = new ByteArrayInputStream(exampleXML.getBytes("UTF-8")); 
Document anotherDocument = builder.build(stream); 

對於builder.build()支持的各種參數,您可以通過api docs

+0

感謝您的快速響應。你粘貼的代碼工作正常,使用特定路徑下的文件創建一個新文檔。但在我的情況下,我需要創建/轉換具有XML格式內容的字符串到Document中。 – 2013-03-05 09:03:40

+0

@akhil_gupta我已根據您的要求更新了答案 – AurA 2013-03-05 09:10:37

+0

是的,代碼可以正常工作以從現有的.xml文件創建新文檔。但在這裏我沒有任何XML文件。我從其他地方得到這個字符串(內容爲xml格式)。正如你可以看到它的代碼:String docString = txtEditor.getDocumentProvider()。getDocument( txtEditor.getEditorInput())。get(); – 2013-03-05 09:10:44

6

這是shold比實際的常見問題更容易回答的常見問題解答:How do I build a document from a String?

所以,我創建issue #111

對於它的價值,我以前改善了這種情況的錯誤消息(看到the previous issue #63,現在你應該有一個錯誤,指出:

MalformedURLException mx = new MalformedURLException(
    "SAXBuilder.build(String) expects the String to be " + 
    "a systemID, but in this instance it appears to be " + 
    "actual XML data."); 

底線是,你應該使用:

Document parseddoc = new SaxBuilder().build(new StringReader(myxmlstring)); 

rolfl

+0

其實,看來我粘貼的代碼也工作正常。我的代碼中有其他地方出現問題。但謝謝你看這個。 – 2013-03-05 13:23:00

相關問題