java解析xml字符串 dom4j_通过dom4j解析xml字符串(示例代码)

import java.util.Iterator;

import java.util.List;

import org.dom4j.Attribute;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

public class Test {

@SuppressWarnings("unchecked")

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

String xml = "single_trade_query utf-8 2088001513232645 20090422577264 ";

Document document = DocumentHelper.parseText(xml);

Element root = document.getRootElement();

List elements = root.elements();

for (Iterator it = elements.iterator(); it.hasNext();) {

Element element = it.next();

List attributes = element.attributes();

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

Attribute attribute = attributes.get(i);

if ("service".equals(attribute.getText())) {

System.out.println(element.getName() + "  :  "

+ element.getText());

}

}

}

}

}

或者:

import java.io.StringReader;

import java.util.Iterator;

import java.util.List;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.xml.sax.InputSource;

public class Test {

@SuppressWarnings("unchecked")

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

String xml = "TestServletTestServlettest.TestServlet";

InputSource in = new InputSource(new StringReader(xml));

in.setEncoding("UTF-8");

SAXReader reader = new SAXReader();

Document document = reader.read(in);

Element root = document.getRootElement();

List elements = root.elements();

for(Iterator it = elements.iterator();it.hasNext();){

Element element = it.next();

System.out.println(element.getName()+" : "+element.getTextTrim());

}

}

}

或者增加ID属性,直接通过ID获取某个属性值:

import java.io.StringReader;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.xml.sax.InputSource;

public class Test {

public static void main(String args[]) {

String xml = "single_trade_query utf-8 2088001513232645 20090422577264 ";

InputSource source = new InputSource(new StringReader(xml));

SAXReader reader = new SAXReader();

Document document = null;

try {

document = reader.read(source);

} catch (DocumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Element root = document.getRootElement();

System.out.println(document.elementByID("tt").getTextTrim());

System.out.println(root.elementByID("tt").getTextTrim());

}

}

注意:通过ID获取,元素ID属性名必须为“大写ID”,小写的“id”会认为是普通属性!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值