解析XML
您可能要做的第一件事就是解析某种 XML 文档。这在< dom 4 j >中很容易做到。以下代码演示了如何执行此操作。
import java.net.URL;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
public class Foo {
public Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
}
使用迭代器
可以使用返回标准 Java 迭代器的各种方法来导航文档。例如
public void bar(Document document) throws DocumentException {
Element root = document.getRootElement();
// iterate through child elements of root
for (Iterator<Element> it = root.elementIterator(); it.hasNext();) {
Element element = it.next();
// do something
}
// iterate through child elements of root with element name "foo"
for (Iterator<Element> it = root.elementIterator("foo"); it.hasNext();) {
Element foo = it.next();
// do something
}
// iterate through attributes of root
for (Iterator<Attribute> it = root.attributeIterator(); it.hasNext();) {
Attribute attribute = it.next();
// do something
}
}
使用 XPath 进行强大的导航
在< dom 4 j >中,XPath 表达式可以在Document
或Node
树中的任何一个上进行计算(例如Attribute
, Element
或 ProcessingInstruction
)。这允许使用一行代码在整个文档中进行复杂的导航。例如
public void bar(Document document) {
List<Node> list = document.selectNodes("//foo/bar");
Node node = document.selectSingleNode("//foo/bar/author");
String name = node.valueOf("@name");
}
例如,如果您希望查找XHTML文档中的所有超文本链接,则以下代码即可实现。
public void findLinks(Document document) throws DocumentException {
List<Node> list = document.selectNodes("//a/@href");
for (Iterator<Node> iter = list.iterator(); iter.hasNext();) {
Attribute attribute = (Attribute) iter.next();
String url = attribute.getValue();
}
}
如果您在学习XPath语言时需要任何帮助,我们强烈推荐Zvon 教程,您可以通过示例进行学习。
快速循环
如果您必须遍历大型XMLIterator
文档树,那么为了提高性能,我们建议您使用快速循环方法,这样可以避免为每个循环创建对象的成本。例如
public void treeWalk(Document document) {
treeWalk(document.getRootElement());
}
public void treeWalk(Element element) {
for (int i = 0, size = element.nodeCount(); i < size; i++) {
Node node = element.node(i);
if (node instanceof Element) {
treeWalk((Element) node);
}
else {
// do something…
}
}
}
创建新的 XML 文档
通常在< dom 4 j >中,您需要从头开始创建一个新文档。这是这样做的一个例子。
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class Foo {
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("author")
.addAttribute("name", "James")
.addAttribute("location", "UK")
.addText("James Strachan");
Element author2 = root.addElement("author")
.addAttribute("name", "Bob")
.addAttribute("location", "US")
.addText("Bob McWhirter");
return document;
}
}
将文档写入文件
Document
将 a (或任何Node
)写入 a 的一种快速而简单的方法Writer
是通过write()
方法。
FileWriter out = new FileWriter("foo.xml");
document.write(out);
out.close();
如果您希望能够更改输出的格式,例如漂亮的打印或紧凑格式,或者您希望能够使用Writer
对象或OutputStream
对象作为目标,那么您可以使用该类XMLWriter
。
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Foo {
public void write(Document document) throws IOException {
// lets write to a file
try (FileWriter fileWriter = new FileWriter("output.xml")) {
XMLWriter writer = new XMLWriter(fileWriter);
writer.write( document );
writer.close();
}
// Pretty print the document to System.out
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter(System.out, format);
writer.write( document );
// Compact format to System.out
format = OutputFormat.createCompactFormat();
writer = new XMLWriter(System.out, format);
writer.write(document);
writer.close();
}
}
与字符串之间的转换
Document
如果您有对 a或任何其他Node
(例如Attribute
or )的引用Element
,则可以通过该asXML()
方法将其转换为默认 XML 文本。
Document document = …;
String text = document.asXML();
如果您有一些 XML 作为 a,您可以使用帮助器方法String
将其重新解析回 aDocumentDocumentHelper.parseText()
String text = "<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);
Document
使用 XSLT 转换
使用Oracle 的JAXP API在 a 上应用XSLTDocument
非常简单。这允许您使用任何 XSLT 引擎,例如Xalan或Saxon。以下是使用 JAXP 创建转换器,然后将其应用到. Document
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import org.dom4j.Document;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
public class Foo {
public Document styleDocument(Document document, String stylesheet) throws Exception {
// load the transformer using JAXP
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(stylesheet));
// now lets style the given document
DocumentSource source = new DocumentSource(document);
DocumentResult result = new DocumentResult();
transformer.transform(source, result);
// return the transformed document
Document transformedDoc = result.getDocument();
return transformedDoc;
}
}
Maven 工件签名
Maven 存储库中的所有工件均使用以下 PGP 密钥进行签名:
-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: Thumbprint: 8F9A3C6D105B9F57844A721D79E193516BE7998F
mQENBFWdcSoBCADK8j+0eVZKUGctZo/VaJ/K2Wppx4jEFgih8xiIWREQ9B3QEugJ
mJMWZHhrnHB+sjVx5No482ch6sVhYmC+VMyTdzepItZ8beYa0pnNGJnrFT+HcTOS
g21Ef5e6BRORNho2j9YTvxvjof29XxU4SJFVgffs48jGeJzN1EDmOz4OlZupKGU+
98o+kMKCiFjcf6Vu03asuml97b2fMOJ09n+UQVlZbBR/Yo407ZLkL2Elx47Fz+82
iO+M8w2qNnxT4PA/TLgaVzkVHaR/JIDlQQ4DfuyloQI1hBpMB8f60oukVr5dBGuS
1dPZ1H7td975sLegWoj7CCOFZXrDzYUXwwXPABEBAAG0IEZpbGlwIEppcnPDoWsg
PGZpbGlwQGppcnNhay5vcmc+iQE5BBMBCAAjBQJVnXEqAhsDBwsJCAcDAgEGFQgC
CQoLBBYCAwECHgECF4AACgkQeeGTUWvnmY/Z6wgArX9fzySIVWcqFuhaIlRlib9j
1qE3sSiFVENV4NrCYv+4ZUQUEUvqwX0F4ij+Au9fzvaWb0gT02ErHYJ9UowUgUYb
IdHsifoGh05jZdiClXJutcQHddM+P+ReIAS4/JDlXza1kqa1RRvDh+OtsrDkL1MU
a5T6/KbCWzAj9+96vqa2dLO0mhyrPpVX/hF4tPY6ltGYEXA9N3c83rFmaCZTNM0t
sEQniQMICOMZul2dKJ4Tev12/G9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