2013-02-12 41 views
0

我有以下代碼:添加無效的XML元素的XML文檔的Java

Document mainContent = new Document(); 
Element rootElement = new Element("html"); 
mainContent.setContent(rootElement); 
Element headElement = new Element("head"); 
Element metaElement = new Element("meta"); 
metaElement.setAttribute("content", "text/html; charset=utf-8"); 
headElement.addContent(metaElement); 
rootElement.addContent(headElement); 
org.jdom2.output.Format format = org.jdom2.output.Format.getPrettyFormat().setOmitDeclaration(true); 
XMLOutputter outputter = new XMLOutputter(format); 
System.out.println(outputter.outputString(mainContent)); 

這將產生輸出:

<html> 
    <head> 
    <meta content="text/html; charset=utf-8" /> 
    </head> 
</html> 

現在,我有以下字符串:

String links = "<link src=\"mysrc1\" /><link src=\"mysrc2\" />" 

如何將它添加到HTML元素中,以便輸出結果爲:

<html> 
    <head> 
     <meta content="text/html; charset=utf-8" /> 
     <link src="mysrc1" /> 
     <link src="mysrc2" /> 
    </head> 
</html> 

請注意,它不是一個有效的XML元素,但每個鏈接都是有效的XML元素。

如果需要,我不介意使用另一個XML解析器。如果有幫助,我已經在我的代碼HTMLCleaner中使用了其他地方。

回答

1

你可以做一些像他們提到的here。基本上把你的XML片段根元素中:

links ="<root>"+links+"</root>"; 
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
factory.setNamespaceAware(false); 
DocumentBuilder builder = factory.newDocumentBuilder(); 
Document doc=builder.parse(links ByteArrayInputStream(xml.getBytes())); 
NodeList nl = ((Element)doc.getDocumentElement()).getChildNodes(); 
for (int temp = 0; temp < nl .getLength(); temp++) { 
Node nNode = nl .item(temp); 
    //Here you create your new Element based on the Node nNode, and the add it to the new DOM you're building 

} 

然後解析鏈接作爲一個有效的XML文檔,並提取所需的節點(基本上什麼除根節點以外)

+0

你是什麼意思的根本提取你想要的節點?它也會刪除根目錄 – Dejell 2013-02-12 16:47:27

+0

請參閱上面的擴展代碼。 – 2013-02-12 16:55:10