包含java.xmldoc的词条

博主:adminadmin 2022-12-05 09:51:10 58

本篇文章给大家谈谈java.xmldoc,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

关于用java创建XML文档的问题

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import org.jdom.Document;

import org.jdom.Element;

import org.jdom.output.Format;

import org.jdom.output.XMLOutputter;

public class GenerateXml {

public static void main(String[] args) {

//初始化3本书籍

GenerateXml gx = new GenerateXml();

Book book1 = gx.new Book("author1", "title1", "publisher1", "subject1",

gx.new PublicationDate("edition1", "isbn1", "date1"));

Book book2 = gx.new Book("author2", "title2", "publisher2", "subject2",

gx.new PublicationDate("edition2", "isbn2", "date2"));

Book book3 = gx.new Book("author3", "title3", "publisher3", "subject3",

gx.new PublicationDate("edition3", "isbn3", "date3"));

ListBook books = new ArrayListBook();

books.add(book1);

books.add(book2);

books.add(book3);

//产生XML,根据List中的对象,打印到控制台,没有生成文件

generateLib(books);

}

static void generateLib(ListBook books) {

Document doc = new Document();

//产生根元素

Element root = new Element("Library");

doc.setRootElement(root);

//循环list,根元素再一一加入book节点

for (Book book : books) {

//生成book节点

Element bookElement = new Element("Book");

bookElement.addContent(new Element("Author").addContent(book

.getAuthor()));

bookElement.addContent(new Element("Title").addContent(book

.getTitle()));

bookElement.addContent(new Element("PublicationDate")

.setAttribute("edition",

book.getPublicationDate().getEdition())

.setAttribute("isbn", book.getPublicationDate().getIsbn())

.addContent(book.getPublicationDate().getDate()));

bookElement.addContent(new Element("Publisher").addContent(book

.getPublisher()));

bookElement.addContent(new Element("Subject").addContent(book

.getSubject()));

//根元素加入一本book

root.addContent(bookElement);

}

XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());

try {

outputter.output(doc, System.out);

} catch (IOException e) {

e.printStackTrace();

}

}

//书类

class Book {

String author;

String title;

String publisher;

String subject;

PublicationDate publicationDate;

public Book() {

super();

}

public Book(String author, String title, String publisher,

String subject, PublicationDate publicationDate) {

super();

this.author = author;

this.title = title;

this.publisher = publisher;

this.subject = subject;

this.publicationDate = publicationDate;

}

public String getAuthor() {

return author;

}

public void setAuthor(String author) {

this.author = author;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getPublisher() {

return publisher;

}

public void setPublisher(String publisher) {

this.publisher = publisher;

}

public String getSubject() {

return subject;

}

public void setSubject(String subject) {

this.subject = subject;

}

public PublicationDate getPublicationDate() {

return publicationDate;

}

public void setPublicationDate(PublicationDate publicationDate) {

this.publicationDate = publicationDate;

}

}

//日期类

class PublicationDate {

String edition;

String isbn;

String date;

public PublicationDate() {

super();

}

public PublicationDate(String edition, String isbn, String date) {

super();

this.edition = edition;

this.isbn = isbn;

this.date = date;

}

public String getEdition() {

return edition;

}

public void setEdition(String edition) {

this.edition = edition;

}

public String getIsbn() {

return isbn;

}

public void setIsbn(String isbn) {

this.isbn = isbn;

}

public String getDate() {

return date;

}

public void setDate(String date) {

this.date = date;

}

}

}

java的xml的解析方式有什么,他们的解析流程是怎么样的,有什么区别

答:4种。(或者说是两种,因为JDOM和DOM4J是DOM的两个特殊情况)

1.SAX解析

解析方式是事件驱动机制!

SAX解析器,逐行读取XML文件解析,每当解析到一个标签的开始/结束/内容/属性时,触发事件。

可以在这些事件发生时,编写程序进行相应的处理。

优点:

分析能够立即开始,而不是等待所有的数据被处理。

逐行加载,节省内存,有助于解析大于系统内存的文档。

有时不必解析整个文档,它可以在某个条件得到满足时停止解析。

缺点:

1.单向解析,无法定位文档层次,无法同时访问同一个文档的不同部分数据(因为逐行解析,当解析第n行时,第n-1行)已经被释放了,无法再对其进行操作)。

2. 无法得知事件发生时元素的层次, 只能自己维护节点的父/子关系。

3. 只读解析方式, 无法修改XML文档的内容。

2. DOM解析

是用与平台和语言无关的方式表示XML文档的官方W3C标准,分析该结构通常需要加载整个 文档和内存中建立文档树模型。程序员可以通过操作文档树, 来完成数据的获取 修改 删除等。

优点:

文档在内存中加载, 允许对数据和结构做出更改。访问是双向的,可以在任何时候在树中双向解析数据。

缺点:

文档全部加载在内存中 , 消耗资源大。

3. JDOM解析

目的是成为Java特定文档模型,它简化与XML的交互并且比使用DOM实现更快。由于是第一 个Java特定模型,JDOM一直得到大力推广和促进。

JDOM文档声明其目的是“使用20%(或更少)的精力解决80%(或更多)Java/XML问题” (根据学习曲线假定为20%)

优点:

使用具体类而不是接口,简化了DOM的API。

大量使用了Java集合类,方便了Java开发人员。

缺点:

没有较好的灵活性。

性能不是那么优异。

4. DOM4J解析

它是JDOM的一种智能分支。它合并了许多超出基本XML文档表示的功能,包括集成的XPath 支持、XML Schema支持以及用于大文档或流化文档的基于事件的处理。它还提供了构建文档表示的选项, DOM4J是一个非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一 个开放源代码的软件。如今你可以看到越来越多的Java软件都在使用DOM4J来读写XML。

目前许多开源项目中大量采用DOM4J , 例如:Hibernate。

JAVA 生成xml格式,具体格式如下,请问JAVA方法怎么写

import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.w3c.dom.*;import org.xml.sax.SAXException;import javax.xml.parsers.*;import javax.xml.transform.*;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.*;import javax.xml.xpath.*;public class Test { public static void main(String[] args) { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); Element theBook=null, theElem=null, root=null; try { factory.setIgnoringElementContentWhitespace(true); DocumentBuilder db=factory.newDocumentBuilder(); Document xmldoc=db.parse(new File("Test1.xml")); root=xmldoc.getDocumentElement(); theBook=(Element) selectSingleNode("/books/book[name='哈里波特']", root); System.out.println("--- 查询找《哈里波特》 ----"); Element nameNode=(Element)theBook.getElementsByTagName("price").item(0); String name=nameNode.getFirstChild().getNodeValue(); System.out.println(name); output(theBook); System.out.println("=============selectSingleNode(books/book[name='哈里波特'], root)=================="); //--- 新建一本书开始 ---- theBook=xmldoc.createElement("book"); theElem=xmldoc.createElement("name"); theElem.setTextContent("新书"); theBook.appendChild(theElem); theElem=xmldoc.createElement("price"); theElem.setTextContent("20"); theBook.appendChild(theElem); theElem=xmldoc.createElement("memo"); theElem.setTextContent("新书的更好看。"); theBook.appendChild(theElem); root.appendChild(theBook); System.out.println("--- 新建一本书开始 ----"); output(xmldoc); System.out.println("=============================="); //--- 新建一本书完成 ---- //--- 下面对《哈里波特》做一些修改。 ---- //--- 查询找《哈里波特》---- //--- 此时修改这本书的价格 ----- theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相当于xpath的".//price"。 System.out.println("--- 此时修改这本书的价格 ----"); output(theBook); //--- 另外还想加一个属性id,值为B01 ---- theBook.setAttribute("id", "B01"); System.out.println("--- 另外还想加一个属性id,值为B01 ----"); output(theBook); //--- 对《哈里波特》修改完成。 ---- //--- 要用id属性删除《三国演义》这本书 ---- theBook=(Element) selectSingleNode("/books/book[@id='B02']", root); System.out.println("--- 要用id属性删除《三国演义》这本书 ----"); output(theBook); theBook.getParentNode().removeChild(theBook); System.out.println("--- 删除后的XML ----"); output(xmldoc); //--- 再将所有价格低于10的书删除 ---- NodeList someBooks=selectNodes("/books/book[price10]", root); System.out.println("--- 再将所有价格低于10的书删除 ---"); System.out.println("--- 符合条件的书有 "+someBooks.getLength()+"本。 ---"); for(int i=0;isomeBooks.getLength();i++) { someBooks.item(i).getParentNode().removeChild(someBooks.item(i)); } output(xmldoc); saveXml("Test1_Edited.xml", xmldoc); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void output(Node node) {//将node的XML字符串输出到控制台 TransformerFactory transFactory=TransformerFactory.newInstance(); try { Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty("encoding", "gb2312"); transformer.setOutputProperty("indent", "yes"); DOMSource source=new DOMSource(); source.setNode(node); StreamResult result=new StreamResult(); result.setOutputStream(System.out); transformer.transform(source, result); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } public static Node selectSingleNode(String express, Object source) {//查找节点,并返回第一个符合条件节点 Node result=null; XPathFactory xpathFactory=XPathFactory.newInstance(); XPath xpath=xpathFactory.newXPath(); try { result=(Node) xpath.evaluate(express, source, XPathConstants.NODE); } catch (XPathExpressionException e) { e.printStackTrace(); } return result; } public static NodeList selectNodes(String express, Object source) {//查找节点,返回符合条件的节点集。 NodeList result=null; XPathFactory xpathFactory=XPathFactory.newInstance(); XPath xpath=xpathFactory.newXPath(); try { result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET); } catch (XPathExpressionException e) { e.printStackTrace(); } return result; } public static void saveXml(String fileName, Document doc) {//将Document输出到文件 TransformerFactory transFactory=TransformerFactory.newInstance(); try { Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); DOMSource source=new DOMSource(); source.setNode(doc); StreamResult result=new StreamResult(); result.setOutputStream(new FileOutputStream(fileName)); transformer.transform(source, result); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } }} XML:?xml version="1.0" encoding="GBK"?booksbookname哈里波特/nameprice10/pricememo这是一本很好看的书。/memo/bookbook id="B02"name三国演义/nameprice10/pricememo四大名著之一。/memo/bookbook id="B03"name水浒/nameprice6/pricememo四大名著之一。/memo/bookbook id="B04"name红楼/nameprice5/pricememo四大名著之一。/memo/book/books

java读取xml文件内容

java中不是有个读取xml文件的类吗?之间调用那类读取出来,然后用取节点的方法去取对应节点的里的值。等下给你代码。

public class ReaderXml {

private static String filename = "E:\\workplace\\readerxml\\bin\\reader\\xml\\reader.xml";

// private static Config config;

public static void main(String []args) throws Exception{

//这里用反射机制

DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();

DocumentBuilder dombuilder=domfac.newDocumentBuilder();

//读取文件流

InputStream is=new FileInputStream(filename);

Document doc=dombuilder.parse(is);

Element root=doc.getDocumentElement();

//获取所有xml节点

NodeList dbinfo=root.getChildNodes();

if(dbinfo!=null){

for(int i=0;idbinfo.getLength();i++){

//获取节点判断

Node db=dbinfo.item(i);

//如果是Hardwares节点,也就是你xml文件的最顶处的节点

if(db.getNodeName().equals("Hardwares")){

//获取第二个节点包含的所有节点

NodeList list=db.getChildNodes();

for(int y=0;ylist.getLength();y++){

Node n=list.item(y);

//如果节点等于Hardware

if(n.getNodeName().equals("Hardware")){

//获取Hardware节点中的所有节点

NodeList CnodeList=n.getChildNodes();

//取出Hardware里面的所有节点

for(int k=0;kCnodeList.getLength();k++){

//取出节点

Node cn=CnodeList.item(k);

//去掉里面的#text文件节点。没用,这个不是你配置的节点,应该是xml文件隐藏的

if(!cn.getNodeName().equals("#text")){

//打印你所配置的所有节点 System.out.println("node["+k+"]="+cn.getNodeName()+" nodeValue["+k+"]="+cn.getTextContent());

}

}

}

}

}

}

}

}

}

//具体你要干嘛自己弄了!

在java中解析xml文档的问题

我给你个例子吧。。。

import javax.xml.parsers.*;

import org.w3c.dom.*;

import org.xml.sax.SAXException;

import java.io.*;

public class XMLUtil

{

//该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象

public static Object getBean()

{

try

{

//创建文档对象

DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = dFactory.newDocumentBuilder();

Document doc;

doc = builder.parse(new File("config.xml"));

//获取包含类名的文本节点

NodeList nl = doc.getElementsByTagName("className");

Node classNode=nl.item(0).getFirstChild();

String cName=classNode.getNodeValue();

//通过类名生成实例对象并将其返回

Class c=Class.forName(cName);

Object obj=c.newInstance();

return obj;

}

catch(Exception e)

{

e.printStackTrace();

return null;

}

}

}

下面是xml文件

?xml version="1.0"?

config

classNameHaierFactory/className

/config

什么包都不要导,就算在最低级的JCreator中直接编译就可以的。。。自己写个main函数调用一下。。

不懂追问,望采纳。如果要学习类似只是2有视频教程

JAVA如何写XML文件?

import java.io.*;\x0d\x0a \x0d\x0aimport org.dom4j.*;\x0d\x0a import org.dom4j.io.OutputFormat;\x0d\x0a import org.dom4j.io.XMLWriter;\x0d\x0a \x0d\x0apublic class DOM4JTest {\x0d\x0a public static void main(String[] args) {\x0d\x0a Document doc = DocumentHelper.createDocument();\x0d\x0a doc.addProcessingInstruction("xml-stylesheet", "type='text/xsl href='students.xsl'");\x0d\x0a Element root = doc.addElement("students");\x0d\x0a \x0d\x0a Element eltStu1 = root.addElement("student").addAttribute("sn", "01");\x0d\x0a Element eltName1 = eltStu1.addElement("name");\x0d\x0a Element eltAge1 = eltStu1.addElement("age");\x0d\x0a eltName1.setText("张三");\x0d\x0a eltAge1.setText("20");\x0d\x0a \x0d\x0a Element eltStu2 = root.addElement("student").addAttribute("sn", "02");\x0d\x0a Element eltName2 = eltStu2.addElement("name");\x0d\x0a Element eltAge2 = eltStu2.addElement("age");\x0d\x0a eltName2.setText("李四");\x0d\x0a eltAge2.setText("18");\x0d\x0a \x0d\x0a try {\x0d\x0a OutputFormat format = new OutputFormat("\x0d\x0a ", true);\x0d\x0a format.setEncoding("gb2312");\x0d\x0a // 可以把System.out改为你要的流。\x0d\x0a XMLWriter xmlWriter = new XMLWriter(new PrintWriter(System.out), format);\x0d\x0a xmlWriter.write(doc);\x0d\x0a xmlWriter.close();\x0d\x0a } catch (IOException e) {\x0d\x0a e.printStackTrace();\x0d\x0a }\x0d\x0a }\x0d\x0a }

java.xmldoc的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于、java.xmldoc的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-05,除非注明,否则均为首码项目网原创文章,转载请注明出处。