java

 import java.io.File;
import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document;
import org.w3c.dom.Element; public class CreatXML { public static void main(String[] args) {
try { //DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("Languages");
root.setAttribute("cat", "it"); Element lan1 = document.createElement("lan");
lan1.setAttribute("id", "1");
Element name1 = document.createElement("name");
name1.setTextContent("Java");
Element ide1 = document.createElement("ide");
ide1.setTextContent("Eclipse");
lan1.appendChild(name1);
lan1.appendChild(ide1); Element lan2 = document.createElement("lan");
lan2.setAttribute("id", "2");
Element name2 = document.createElement("name");
name2.setTextContent("Swift");
Element ide2 = document.createElement("ide");
ide2.setTextContent("XCode");
lan2.appendChild(name2);
lan2.appendChild(ide2); Element lan3 = document.createElement("lan");
lan3.setAttribute("id", "3");
Element name3 = document.createElement("name");
name3.setTextContent("C#");
Element ide3 = document.createElement("ide");
ide3.setTextContent("Visual Studio");
lan3.appendChild(name3);
lan3.appendChild(ide3); root.appendChild(lan1);
root.appendChild(lan2);
root.appendChild(lan3);
document.appendChild(root); //------------- TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8"); StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
System.out.println(writer.toString()); transformer.transform(new DOMSource(document), new StreamResult(new File("newxml.xml"))); } catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
} }

下载地址

DOM4j的使用

 import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper; public class Test { public static void main(String[] args) {
String xmlString = "<root><people>ACELY</people></root>"; try { Document document = DocumentHelper.parseText(xmlString); System.out.println(document.asXML()); } catch (DocumentException e) {
e.printStackTrace();
}
} }

DOM4j使用文档

Parsing XML

One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.

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;
}
}

Using Iterators

A document can be navigated using a variety of methods that return standard Java Iterators. For example

    public void bar(Document document) throws DocumentException {

        Element root = document.getRootElement();

        // iterate through child elements of root
for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next();
// do something
} // iterate through child elements of root with element name "foo"
for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
Element foo = (Element) i.next();
// do something
} // iterate through attributes of root
for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
// do something
}
}

Powerful Navigation with XPath

In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.

    public void bar(Document document) {
List list = document.selectNodes( "//foo/bar" ); Node node = document.selectSingleNode( "//foo/bar/author" ); String name = node.valueOf( "@name" );
}

For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.

    public void findLinks(Document document) throws DocumentException {

        List list = document.selectNodes( "//a/@href" );

        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Attribute attribute = (Attribute) iter.next();
String url = attribute.getValue();
}
}

If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.

Fast Looping

If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example

    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....
}
}
}

Creating a new XML document

Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.

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;
}
}

Writing a document to a file

A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.

  FileWriter out = new FileWriter( "foo.xml" );
document.write( out );

If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.

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
XMLWriter writer = new XMLWriter(
new FileWriter( "output.xml" )
);
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 );
}
}

Converting to and from Strings

If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.

        Document document = ...;
String text = document.asXML();

If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()

        String text = "<person> <name>James</name> </person>";
Document document = DocumentHelper.parseText(text);

Styling a Document with XSLT

Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a 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;
}
}

java创建XML及开源DOM4J的使用的更多相关文章

  1. 【Java】XML解析之DOM4J

    DOM4J介绍 dom4j是一个简单的开源库,用于处理XML. XPath和XSLT,它基于Java平台,使用Java的集合框架,全面集成了DOM,SAX和JAXP,使用需要引用dom4j.jar包 ...

  2. 当Java遇到XML 的邂逅+dom4j

    XML简介: XML:可扩展标记语言! 01.很象html 02.着重点是数据的保存 03.无需预编译 04.符合W3C标准 可扩展:我们可以自定义,完全按照自己的规则来! 标记: 计算机所能认识的信 ...

  3. 通过Java创建XML(中文乱码已解决)

    package com.zyb.xml; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.Ou ...

  4. Java 创建xml文件和操作xml数据

    java中的代码 import java.io.File; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; ...

  5. Java 读写XML文件 API--org.dom4j

    om4j是一个Java的XML API,类似于jdom,用来读写XML文件的.dom4j是一个十分优秀的JavaXML API,具有性能优异.功能强大和极其易使用的特点,同时它也是一个开放源代码的软件 ...

  6. 使用Java创建XML数据

    ------------siwuxie095                         工程名:TestCreateXML 包名:com.siwuxie095.xml 类名:CreateXML. ...

  7. xml介绍+xml创建+xml读取

    1.xml介绍:(URL:https://blog.csdn.net/weixin_37861326/article/details/81082144) xml是用来传输内容的,是w3c推荐的 2.使 ...

  8. Java XML解析工具 dom4j介绍及使用实例

    Java XML解析工具 dom4j介绍及使用实例 dom4j介绍 dom4j的项目地址:http://sourceforge.net/projects/dom4j/?source=directory ...

  9. Java进阶(二十七)使用Dom4j解析XML文件

    使用Dom4j解析XML文件 写在前面的话 由于论文实验要求,需要实现操作XML文档,为此想到了dom4j这个工具,使用之后深感受益.在此分享给大家,以此共勉. 注:本文转载自http://blog. ...

随机推荐

  1. 大牛对ACM入门菜鸟的一些话

    首先就是我为什么要写这么一篇日志.原因很简单,就是因为前几天有个想起步做ACM人很诚恳的问我该如何入门.其实就现在而言,我并不是很想和人再去讨论这样的话题,特别是当我发现我有很多的东西要学的时候,我实 ...

  2. HTML5 ArrayBuffer:类型化数组 (二)

    类型化数组是JavaScript操作二进制数据的一个接口. 这要从WebGL项目的诞生说起,所谓WebGL,就是指浏览器与显卡之间的通信接口,为了满足JavaScript与显卡之间大量的.实时的数据交 ...

  3. (转)DEDECMS模板原理、模板标签学习 - .Little Hann

    本文,小瀚想和大家一起来学习一下DEDECMS中目前所使用的模板技术的原理: 什么是编译式模板.解释式模板,它们的区别是什么? 模板标签有哪些种类,它们的区别是什么,都应用在哪些场景? 学习模板的机制 ...

  4. APP长时间处于后台,再次调用时提示用户重新登录

    第一步:当应用被处于后台时,调用计时器的start()方法,开始计时 在所有Activity继承的BaseSwiBackAct中的 public void onStop() { EventBus.ge ...

  5. WPF 弱事件

    因为在接触WPF的过程中追查INotifyPropertyChanged的通知原理的时候,发现了 PropertyChangedEventManager这个类,它是继承与WeakEventManage ...

  6. 利用js加载本地图片预览功能

    直接上代码: 经测试,除safari6包括6以下不支持,其他均可正常显示. 原因:safari6不支持filereader,同时不能使用IE滤镜导致失效. fix: 可以利用canvas,解决safa ...

  7. CMake交叉编译配置

    很多时候,我们在开发的时候是面对嵌入式平台,因此由于资源的限制需要用到相关的交叉编译.即在你host宿主机上要生成target目标机的程序.里面牵扯到相关头文件的切换和编译器的选择以及环境变量的改变等 ...

  8. protobuf的反射机制

    反射机制 java在运行状态时,能够知道任意类的所有属性和方法,都能够调用任意对象的任意方法和属性.这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制. C++本身没有反射机制. ...

  9. 08_linux下安装chrome

    首先下载chrome,需要改hosts哦(o(^▽^)o,别告诉我你不会,可以问度娘.谷哥哦) 下载地址:https://dl.google.com/linux/direct/google-chrom ...

  10. 转型函数 Boolean()

    布尔值有2种可能的值true和false;但 ECMAScript中所有类型的值都有与这两个 Boolean 值 等价的值.要将一个值转换为其对应的 Boolean 值,可以调用转型函数 Boolea ...