2013-02-12 58 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