将无效的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中的其他地方使用了。

你可以做他们在这里提到的事情。基本上将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文档,并提取所需的节点(基本上是根节点以外的任何节点)

最新更新