0

我有以下代码:

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

4

1 回答 1

1

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

于 2013-02-12T16:41:30.490 回答