I have the following code:
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));
This will produce the output :
<html>
<head>
<meta content="text/html; charset=utf-8" />
</head>
</html>
Now, I have the following string:
String links = "<link src=\"mysrc1\" /><link src=\"mysrc2\" />"
How can I add it to the HTML element so the output will be:
<html>
<head>
<meta content="text/html; charset=utf-8" />
<link src="mysrc1" />
<link src="mysrc2" />
</head>
</html>
Please note that it's NOT a valid XML element altogether, but each link is a valid XML Element.
I don't mind using another XML parser if needed. I am already using somewhere else in my code HTMLCleaner if it helps.
You can do something like they mention here. Basically place your xml snippet inside of a root element:
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
}
Then parse links as a valid XML document, and extract the nodes you want (basically anything other than the root node)