[英]Add invalid xml elements to xml document java
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元素中,以便输出为:
<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. 请注意,它完全不是有效的XML元素,但是每个链接都是有效的XML元素。
I don't mind using another XML parser if needed. 如果需要,我不介意使用其他XML解析器。 I am already using somewhere else in my code HTMLCleaner if it helps.
如果有帮助,我已经在代码HTMLCleaner中使用了其他地方。
You can do something like they mention here . 您可以做他们在这里提到的事情 。 Basically place your xml snippet inside of a root element:
基本上将您的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
}
Then parse links as a valid XML document, and extract the nodes you want (basically anything other than the root node) 然后将链接解析为有效的XML文档,并提取所需的节点(基本上是除根节点以外的所有节点)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.