将无效的xml元素添加到xml文档java中

时间:2013-02-12 16:23:08

标签: java xml xml-parsing jdom-2

我有以下代码:

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 个答案:

答案 0 :(得分: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文档,并提取所需的节点(基本上不是根节点)