向xml文档java添加无效的xml元素
我有以下代码:向xml文档java添加无效的xml元素,java,xml,xml-parsing,jdom-2,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", "
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\" />"
String links=“”
如何将其添加到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
}
links=“”+links+”;
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder=factory.newDocumentBuilder();
Document doc=builder.parse(links ByteArrayInputStream(xml.getBytes());
NodeList nl=((元素)doc.getDocumentElement()).getChildNodes();
对于(int-temp=0;temp
然后将链接解析为有效的XML文档,并提取所需的节点(基本上是根节点以外的任何节点)提取所需的节点是什么意思?它也会移除根