百度
360搜索
搜狗搜索

dom4j解析xml文件,JAVA中如何用DOM4J将一个字符串解析成XML格式详细介绍

本文目录一览: 怎样应用Dom4j对自动化生成的XML文件进行解析

是的,dom4j既可以解析xml文档,也可以创建xml文档。使用dom4j必须导入dom4j的jar包。
以下是用dom4j来解析xml文件生成另一个xml文档的过程,我在这里只是将新生成的xml的文档打印,dom4j也可以新生成的xml的文档保存到磁盘。
import java.io.File;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class DomTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
//读取xml文件信息
File inputXml=new File("D:/test.xml");
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
//获取根节点

元素

Element root = document.getRootElement();

//创建xml文档

Document doc = DocumentHelper.createDocument();

//创建表格的根节点

元素的子节点

元素列表

Iterator iter = root.elementIterator("row");

//循环列表

while(iter.hasNext()) {

//得到每个

元素

Element rowEle=(Element)iter.next();

//创建表格中的行

元素Element rootElement = DocumentHelper.createElement("table");doc.setRootElement(rootElement);//获取根节点

元素Element trElement = rootElement.addElement("tr");//创建表格中行
元素的子元素列

元素
//第一列存储

元素的ballsnum属性值

Element ballsnum = trElement.addElement("td");

ballsnum.addText(rowEle.attributeValue("ballsnum"));

//第二列存储

元素的opentime属性值

Element opentime = trElement.addElement("td");

opentime.addText(rowEle.attributeValue("opentime"));

//第三列存储

元素的opencode属性值

Element opencode = trElement.addElement("td");

opencode.addText(rowEle.attributeValue("opencode"));

//第四列存储

元素的expect属性值

Element expect = trElement.addElement("td");

expect.addText(rowEle.attributeValue("expect"));

}

System.out.println(doc.asXML());

} catch (Exception e) {

e.printStackTrace();

}

}

}

我将

存储在D盘下的test.xml文件中

我读取D盘下的test.xml文件中的xml内容生成了一个表格

System.out.println(doc.asXML());语句将在控制台打印表格内容

打印结果如下:

3 2014-01-19 21:30:00 05,14,16,21,29,30|12 14008
3 2014-01-16 21:30:00 08,10,12,14,18,28|14 14007

java中dom4j解析xml文件怎么获取节点属性

java读取xml节点元素,主要使用java提供的解析xml的工具类SAXParserFactory,如下代码:package xml.xmlreader;import java.io.File;import java.net.URL;import java.util.Properties;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;public class CFGParser {//解析xml文件的工具类 private Properties props; public Properties getProps() { return props; } public void setProps(Properties props) { this.props = props; } public void parse(String filename) throws Exception { CFGHandler handler = new CFGHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); URL confURL = super.getClass().getClassLoader().getResource(filename); if (confURL == null) { System.out.println("Can't find configration file."); return; } try { parser.parse(confURL.toString(), handler); this.props = handler.getProps(); } finally { factory = null; parser = null; handler = null; } } public void parseFile(String filename) throws Exception { CFGHandler handler = new CFGHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); File f = new File(filename); if ((f == null) || (!f.exists())) return; try { parser.parse(f, handler); this.props = handler.getProps(); } finally { factory = null; parser = null; handler = null; } }}package xml.xmlreader;import java.util.Properties;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class CFGHandler extends DefaultHandler{ private Properties props; private String currentSet; private String currentName; private StringBuffer currentValue = new StringBuffer(); public CFGHandler() { this.props = new Properties(); } public Properties getProps() { return this.props; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.currentValue.delete(0, this.currentValue.length()); this.currentName = qName; } public void characters(char[] ch, int start, int length) throws SAXException { this.currentValue.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { this.props.put(qName.toLowerCase(), this.currentValue.toString().trim()); }}xml文件 6 10 23:00 12:00 18:00jsp获取各个节点的值:

用dom4j解析xml报错: Error on line 1 of document : Content is not allowed in prolog。

将头标记改为

在JAVA web项目中,如果用dom4j来操作xml文件,应该怎么写SAXReader.read(“路径”),这个路径该怎么写

可以参考 :
package com.zuxia.dom4j;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*
* 使用dom4j解析xml
*
* 1. 创建解析器
*
* 2. 创建文档对象Document
*
* 3. 获取根节点
*
*/
public class Dom4jParseXML {
public static void main(String[] args) {

//1. 创建解析器
SAXReader saxreader = new SAXReader();

Document doc = null;
try {
//2. 创建文档对象Document
doc = saxreader.read(new File("src/studentinfo.xml"));
} catch (Exception e) {
System.out.println("读取xml文件异常!");
}

//3. 获取根节点
Element root = doc.getRootElement();

//4. 获取元素
Iterator

iter = root.elementIterator();

while(iter.hasNext()){

Element student = iter.next();

System.out.println("学号:"+student.attributeValue("stuno")+"\t姓名:"+student.elementText("name"));

}

//提示用户添加新的数据

Scanner sc = new Scanner(System.in);

System.out.println("请输入学号:");

String stuno = sc.nextLine();

System.out.println("请输入姓名:");

String name = sc.nextLine();

System.out.println("请输入年龄:");

String age = sc.nextLine();

//将数据添加在Document中

Element student = root.addElement("student");

student.addAttribute("stuno", stuno);

student.addElement("name").addText(name);

student.addElement("age").addText(age);

//3. 设置格式

OutputFormat format = OutputFormat.createCompactFormat();

format.setIndentSize(4);

format.setNewlines(true);

try {

//4. 保存xml文件

XMLWriter out = new XMLWriter(new FileOutputStream("src/studentinfo.xml"),format);

out.write(doc);

System.out.println("ok!!!");

} catch (Exception e) {

System.out.println("失败!");

}

System.out.println("完成了!");

}

}

java中dom4j解析xml的问题,请大侠们帮帮忙

pull解析xml也挺简单的。推荐哟
List

nodes=doc.selectNodes();

int count=nodes.size();

for(int i=0;i
<count;i++){
Node node=nodes.get(i);

//.....doSomeThing

}

完善一下:

String xmlStr="";

SAXReader reader=new SAXReader();

try {

Document doc=(Document)reader.read(xmlStr);

List

nodes=doc.selectNodes("FieldArray/FIELD");

int count=nodes.size();

List
<map
> list=new ArrayList
<map
>();

for(int i=0;i
<count;i++){
Map

map=new HashMap

();

Element e=(Element)nodes.get(i);

String name=e.attributeValue("Name");

map.put("name", "name");

//...........do some thing

}

} catch (DocumentException e) {

e.printStackTrace();

}

</count;i++){
</map
</map

</count;i++){

java中dom4j解析xml文件怎么获取节点属性

java读取xml节点元素,主要使用java提供的解析xml的工具类SAXParserFactory,如下代码:package
xml.xmlreader;import
java.io.File;import
java.net.URL;import
java.util.Properties;import
javax.xml.parsers.SAXParser;import
javax.xml.parsers.SAXParserFactory;public
class
CFGParser
{//解析xml文件的工具类
private
Properties
props;
public
Properties
getProps()
{
return
props;
}
public
void
setProps(Properties
props)
{
this.props
=
props;
}
public
void
parse(String
filename)
throws
Exception
{
CFGHandler
handler
=
new
CFGHandler();
SAXParserFactory
factory
=
SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser
parser
=
factory.newSAXParser();
URL
confURL
=
super.getClass().getClassLoader().getResource(filename);
if
(confURL
==
null)
{
System.out.println("Can't
find
configration
file.");
return;
}
try
{
parser.parse(confURL.toString(),
handler);
this.props
=
handler.getProps();
}
finally
{
factory
=
null;
parser
=
null;
handler
=
null;
}
}
public
void
parseFile(String
filename)
throws
Exception
{
CFGHandler
handler
=
new
CFGHandler();
SAXParserFactory
factory
=
SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParser
parser
=
factory.newSAXParser();
File
f
=
new
File(filename);
if
((f
==
null)
||
(!f.exists()))
return;
try
{
parser.parse(f,
handler);
this.props
=
handler.getProps();
}
finally
{
factory
=
null;
parser
=
null;
handler
=
null;
}
}}package
xml.xmlreader;import
java.util.Properties;import
org.xml.sax.Attributes;import
org.xml.sax.SAXException;import
org.xml.sax.helpers.DefaultHandler;public
class
CFGHandler
extends
DefaultHandler{
private
Properties
props;
private
String
currentSet;
private
String
currentName;
private
StringBuffer
currentValue
=
new
StringBuffer();
public
CFGHandler()
{
this.props
=
new
Properties();
}
public
Properties
getProps()
{
return
this.props;
}
public
void
startElement(String
uri,
String
localName,
String
qName,
Attributes
attributes)
throws
SAXException
{
this.currentValue.delete(0,
this.currentValue.length());
this.currentName
=
qName;
}
public
void
characters(char[]
ch,
int
start,
int
length)
throws
SAXException
{
this.currentValue.append(ch,
start,
length);
}
public
void
endElement(String
uri,
String
localName,
String
qName)
throws
SAXException
{
this.props.put(qName.toLowerCase(),
this.currentValue.toString().trim());
}}xml文件
6
10
23:00
12:00
18:00jsp获取各个节点的值:
dom4j中,使用Element.attributes方法可以获取到节点的属性,而使用elements则可以获取相应的子节点
比如:
Element root = doc.getRootElement();
List attrList = root.attributes();
for (int i = 0; i < attrList.size(); i++) {
//属性的取得
Attribute item = (Attribute)attrList.get(i);
System.out.println(item.getName() + "=" + item.getValue());
}
List childList = root.elements();
for (int i = 0; i < childList.size(); i++) {
//子节点的操作
Element it = (Element) childList.get(i);
//对子节点进行其它操作...
}

JAVA中如何用DOM4J将一个字符串解析成XML格式

用:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xmlStr.getBytes()));
试试。
String xmlStr="

a

bcd";

看看

dom4j解析xml文件,将内容显示在jsp如何做?

SAXReader reader = new SAXReader();// 实例化解析器
File file = new File("路径");
Document doc = reader.read(file);
Element root = doc.getRootElement();// 得到根节点
List childList = root.elements(); //获取所有子节点
Element rsElement = root.element("rs");//获取rs节点
//获取子节点属性名、值
List attrList = root.attributes();
for (int i = 0; i < attrList.size(); i++) {
Attribute item = (Attribute)attrList.get(i);
System.out.println(item.getName() + "=" + item.getValue());
}
SAXReader reader = new SAXReader();// 实例化解析器
File file = new File("路径");
Document doc = reader.read(file);
Element root = doc.getRootElement();// 得到根节点
其他的,自己去参考吧,不是太难,相信你可以的!
jsp中解析dom不推荐,建议在后台用DOM取好后返回给前台jsp页面显示:
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Baidu {
public static void main(String[] args) throws Exception {
List

list = display();

Map

map = run(list);

for (int i = 0; i < list.size(); i++) {

System.out.println(list.get(i) + "--" +map.get(list.get(i)));

}

}

private static String path;

static {

path = Baidu.class.getResource("/test.xml").getPath();

try {

path = URLDecoder.decode(path, "utf-8");

} catch (UnsupportedEncodingException e) {

throw new RuntimeException(e);

}

}

// 得到normativeField中每项的值

public static List

display() throws Exception{

Document doc = getDocument(path);

NodeList list = doc.getElementsByTagName("normativeField");

List

normativeFieldList = new ArrayList

();

// 得到normativeField中每项的值加到normativeFieldList集合里

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

normativeFieldList.add(list.item(i).getTextContent());

}

return normativeFieldList;

}

public static Map

run(List

list) throws Exception {

Map

map = new HashMap

();

Document doc = getDocument(path);

for (int i = 0; i < list.size(); i++) {

NodeList nodeListlist = doc.getElementsByTagName(list.get(i));

Element e = (Element) nodeListlist.item(0);

String value = e.getAttribute("value");

map.put(list.get(i), value);

}

return map;

}

public static Document getDocument(String path) throws Exception {

Document doc = DocumentBuilderFactory.newInstance()

.newDocumentBuilder().parse(path);

return doc;

}

}

控制台:

ID--eye1.id

xingming--eye1.name

xingbie--eye1.sex

nianling--eye1.age

shili--eye2.eyelight

shengao--eye2.high

tizhong--eye2.wealth

guomin--

gongfeizifei--eye1.pay

lianxifangshi--eye1.telephonenumber

bingli--eye1.content1

test.xml要在工程根目录下:

relation

ID

xingming

xingbie

nianling

shili

shengao

tizhong

guomin

gongfeizifei

lianxifangshi

bingli

eye1

eye2

dom4j 解析xml 获取不到根节点

import java.io.File;import java.util.Iterator;
import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class Xstream { @SuppressWarnings("rawtypes") public static void xmlPrase(String xml){ try {// Document document=DocumentHelper.parseText(xml);//解析字符串 SAXReader reader = new SAXReader(); //解析xml文件 Document document = reader.read(new File("/test/test.xml"));//解析xml文件
Element rootElt = document.getRootElement(); Iterator bodyIter = rootElt.elementIterator(); while(bodyIter.hasNext()){ Element oe = (Element) bodyIter.next(); if(oe.getName().equals("brank")) System.out.println(oe.getStringValue()); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args){ xmlPrase(""); } //xml文件 如下/*

a

b

c

d

e

*/}
获取根节点,System.out.println(rootElm.getName()),不是getTest()

dom4j解析无根节点的xml

public static void main(String[] args) {
SAXReader saxReader = new SAXReader();
Document document;
try {
document = saxReader.read(new File(Dom4jParse.class.getClass()
.getResource("/").getFile().toString()
+ "test.xml"));
Element root = document.getRootElement();
List list = new ArrayList();
//List里存放的是BEAN对象的值
new Dom4jParse().parse(root , list);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Bean bean = (Bean) iterator.next();
System.out.println("ID:" + bean.getId() + "\nAge:" + bean.getAge() + "\nName:" + bean.getName());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 获得X属性结果是X值的整个标签
*/
public void parse(Element node ,List list) {
Iterator iters = node.elementIterator("cdr");
while(iters.hasNext()){
Element itemEle = (Element) iters.next();
Bean bean = new Bean();
bean.setId(itemEle.elementText("ID") != null ? itemEle.elementText("ID") : "");
bean.setAge(itemEle.elementText("Name") != null ?itemEle.elementText("Name") : "");
bean.setName(itemEle.elementText("Age") != null ?itemEle.elementText("Age") : "");
list.add(bean);
}
}
简单了点,自己去加强

少长咸集

© 2025 Copyright Your WebSite.Some Rights Reserved.

Powered By Theme By


阅读更多 >>>  编程语言都有什么b

网站数据信息

"dom4j解析xml文件,JAVA中如何用DOM4J将一个字符串解析成XML格式"浏览人数已经达到21次,如你需要查询该站的相关权重信息,可以点击进入"Chinaz数据" 查询。更多网站价值评估因素如:dom4j解析xml文件,JAVA中如何用DOM4J将一个字符串解析成XML格式的访问速度、搜索引擎收录以及索引量、用户体验等。 要评估一个站的价值,最主要还是需要根据您自身的需求,如网站IP、PV、跳出率等!