以下示例演示如何读取xml元素的混合内容。混合内容可以具有多种类型的内容,例如文本(Text),注释(Comment),CDATA(CDATA)或某些子元素(Element)。
您还看到,可以像调用数据集一样通过调用remove方法来从元素中删除混合的内容List。
package org.nhooo.example.jdom; import org.jdom2.*; import org.jdom2.input.SAXBuilder; import java.io.IOException; import java.io.StringReader; import java.util.List; public class JDOMMixedContent { public static void main(String[] args) { String xml = "<root>" + " <data>" + " <!-- This element contains application data -->" + " User Information" + " <![CDATA[<table><tr><td>-data-</td></tr></table>]]>" + " <field name=\"username\">alice</field>" + " </data>" + "</root>"; SAXBuilder builder = new SAXBuilder(); try { Document document = builder.build(new StringReader(xml)); Element root = document.getRootElement(); Element data = root.getChild("data"); // 读取xml元素的混合内容并进行迭代 //结果列表。此列表对象可以包含任何 // 以下对象:Comment,Element,CDATA,DocType, // ProcessingInstruction,EntityRef和Text。 List content = data.getContent(); for (Object o : content) { if (o instanceof Comment) { Comment comment = (Comment) o; System.out.println("Comment = " + comment); } else if (o instanceof Element) { Element element = (Element) o; System.out.println("Element = " + element); } else if (o instanceof CDATA) { CDATA cdata = (CDATA) o; System.out.println("CDATA = " + cdata); } else if (o instanceof DocType) { DocType docType = (DocType) o; System.out.println("DocType = " + docType); } else if (o instanceof ProcessingInstruction) { ProcessingInstruction pi = (ProcessingInstruction) o; System.out.println("PI = " + pi); } else if (o instanceof EntityRef) { EntityRef entityRef = (EntityRef) o; System.out.println("EntityRef = " + entityRef); } else if (o instanceof Text) { Text text = (Text) o; System.out.println("Text = " + text); } } // 删除第二个混合内容,即CDATA内容。 content.remove(2); } catch (JDOMException | IOException e) { e.printStackTrace(); } } }
这是我们程序的结果:
Text = [Text: ] Comment = [Comment: <!-- This element contains application data -->] Text = [Text: User Information ] CDATA = [CDATA: <table><tr><td>-data-</td></tr></table>] Text = [Text: ] Element = [Element: <field/>] Text = [Text: ]
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>