【问题标题】:Add invalid xml elements to xml document java将无效的 xml 元素添加到 xml 文档 java
【发布时间】:2013-02-12 16:23:07
【问题描述】:

我有以下代码:

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

【问题讨论】:

    标签: java xml xml-parsing jdom-2


    【解决方案1】:

    你可以做他们提到的here。基本上将您的 xml sn-p 放在根元素内:

    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 文档,并提取您想要的节点(基本上除了根节点之外的任何节点)

    【讨论】:

    • 提取你想要的节点是什么意思?它也会删除根
    最近更新 更多