求解析如下xml?

doingjava 2009-05-12 02:35:57
"<?xml version='1.0' encoding='GBK'?>" +
"<xml>" +
"<message>获取成功</message>" +
"<person>" +

"<teacher>" +
"<name>Gavin</name>" +
"<age>23</age>" +
"<sex>男</sex>" +
"</teacher>" +

"<teacher>" +
"<name>kathy</name>" +
"<age>21</age>" +
"<sex>女</sex>" +
"</teacher>" +

"</person>" +
"</xml>";

分别将两条遍历输出:
name:
age:
sex:
...全文
132 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
valen_jia 2009-05-13
  • 打赏
  • 举报
回复
应楼主要求,用dom4j给你写了个

package test;

import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jParseXml {
public static void main(String[] args) {
String xmlString = "<?xml version='1.0' encoding='GBK'?>" + " <person>"
+ " <teacher>" + " <name>Gavin </name>" + " <age>23 </age>"
+ " <sex>男 </sex>" + " </teacher>" + " <teacher>"
+ " <name>kathy </name>" + " <age>21 </age>" + " <sex>女 </sex>"
+ " </teacher>" + " </person>";
SAXReader reader = new SAXReader();
Document document;
try {
document = DocumentHelper.parseText(xmlString);
Element root = document.getRootElement();
List<Element> list = root.elements("teacher");
for (int i = 0; i < list.size(); i++) {
Element teacher = list.get(i);
List<Element> property = teacher.elements();
for (int j = 0; j < property.size(); j++) {
Element e = property.get(j);
System.out.print(e.getQName().getName() + ":"
+ teacher.elementText(e.getQName().getName())
+ "\t");
}
System.out.println();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}

valen_jia 2009-05-12
  • 打赏
  • 举报
回复
3

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class ParseXmlString {
public static void main(String[] args) {
String xmlstring = "<?xml version='1.0' encoding='GBK'?>" +

" <person>" +

" <teacher>" +
" <name>Gavin </name>" +
" <age>23 </age>" +
" <sex>男 </sex>" +
" </teacher>" +

" <teacher>" +
" <name>kathy </name>" +
" <age>21 </age>" +
" <sex>女 </sex>" +
" </teacher>" +

" </person>" ;

parse(xmlstring);
}

// 通过Jdom来实现解析
public static void parse(String xmlstring) {
SAXBuilder builder = new SAXBuilder();
try {
//创建xml文档对象
Document doc = builder.build(new StringReader(xmlstring));
//根节点
Element root = doc.getRootElement();
//拿到teacher节点
List<Element> children = root.getChildren("teacher");
for (int i = 0; i < children.size(); i++) {
Element e = children.get(i);
List<Element> a = e.getChildren();
for(int j = 0;j<a.size();j++){
Element ee = a.get(j);
System.out.print(ee.getName()+":"+ee.getText()+"\t");
}
System.out.println();
}
} catch (JDOMException e) {
e.printStackTrace();
}
}
}


qiheia 2009-05-12
  • 打赏
  • 举报
回复
用dom4j去解析XML
oxcow 2009-05-12
  • 打赏
  • 举报
回复
dom解析,给个例子,照着弄就行了。

ballot.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<ballot>
<subject>你喜欢什么颜色</subject>
<options att="only">
<option amount="0">黑色</option>
<option amount="0">白色</option>
<option amount="0">红色</option>
<option amount="0">绿色</option>
</options>
<validityDate>
<startDate>2008-08-09</startDate>
<endDate>2009-08-09</endDate>
</validityDate>
</ballot>


bean对象 这里为ballot

public class BallotBean {
private String subject;
private String[] options = { "黑色", "白色", "红色", "绿色" };
private String[] amount;
private String startDate;
private String endDate;
private String att;

public BallotBean() {

}
//... 省掉set、get方法
}


解析代码片段

/**
* 解析 ballot.xml
* @param inFile 文件路径
* @param ballotBean 输入文档对象
* @throws Exception
*/
public static void readBallotXML(String inFile, BallotBean ballotBean)
throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (DOMException de) {
de.printStackTrace();
}
Document doc = null;
try {
doc = (Document) db.parse(inFile);
} catch (DOMException de) {
de.printStackTrace();
}
Element root = doc.getDocumentElement();

NodeList subjects = root.getElementsByTagName("subject");
Element subject = (Element) subjects.item(0);
Text ts = (Text) subject.getFirstChild();
ballotBean.setSubject(ts.getNodeValue());

NodeList optionsN = root.getElementsByTagName("options");
Element optionN = (Element) optionsN.item(0);
ballotBean.setAtt(optionN.getAttribute("att"));
NodeList options = optionN.getElementsByTagName("option");
String s[] = new String[options.getLength()];
String amounts[] = new String[options.getLength()];
for (int i = 0; i < options.getLength(); i++) {
Element optionE = (Element) options.item(i);
amounts[i] = optionE.getAttribute("amount");
Text t = (Text) optionE.getFirstChild();
s[i] = t.getNodeValue();
}
ballotBean.setOptions(s);
ballotBean.setAmount(amounts);

NodeList validityDate = root.getElementsByTagName("validityDate");
Element validityDateN = (Element) validityDate.item(0);

NodeList st = validityDateN.getElementsByTagName("startDate");
Element stt = (Element) st.item(0);
Text tss = (Text) stt.getFirstChild();
ballotBean.setStartDate(tss.getNodeValue());

NodeList et = validityDateN.getElementsByTagName("endDate");
Element ett = (Element) et.item(0);
Text tee = (Text) ett.getFirstChild();
ballotBean.setEndDate(tee.getNodeValue());
}


令附写方法片段

/**
* 写 ballot xml类型的文件
*
* @param outFile
* 输入文件名
* @param ballotBean
* 数据
* @throws Exception
*/
public static void writeBallotXML(String outFile, BallotBean ballotBean)
throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (DOMException de) {
de.printStackTrace();
}
Document doc = null;
doc = db.newDocument();
Element root = doc.createElement("ballot");
doc.appendChild(root);

Element subject = doc.createElement("subject");
Text subjectContent = doc.createTextNode(ballotBean.getSubject());
subject.appendChild(subjectContent);
root.appendChild(subject);

Element options = doc.createElement("options");
options.setAttribute("att", ballotBean.getAtt());
root.appendChild(options);
String[] ops = ballotBean.getOptions() == null ? new String[1]
: ballotBean.getOptions();
String[] ams = ballotBean.getAmount() == null ? new String[1]
: ballotBean.getAmount();

for (int i = 0; i < ops.length; i++) {
Element option = doc.createElement("option");
option.setAttribute("amount", ams[i]);
Text toption = doc.createTextNode(ops[i]);
option.appendChild(toption);
options.appendChild(option);
}

Element validityDate = doc.createElement("validityDate");
root.appendChild(validityDate);

Element startDate = doc.createElement("startDate");
Text tsd = doc.createTextNode(ballotBean.getStartDate());
startDate.appendChild(tsd);
validityDate.appendChild(startDate);

Element endDate = doc.createElement("endDate");
Text ted = doc.createTextNode(ballotBean.getEndDate());
endDate.appendChild(ted);
validityDate.appendChild(endDate);

File f = new File(outFile);
if (!f.exists()) {
f.createNewFile();
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
OutputStreamWriter op = new OutputStreamWriter(new FileOutputStream(f),
"utf-8");
StreamResult result = new StreamResult(op);
transformer.transform(source, result);
op.flush();
op.close();
}


当然也可以用其他除过w3c的dom解析,比如SAX,dom4j,具体方法可以google到
doingjava 2009-05-12
  • 打赏
  • 举报
回复
不好意思,没说清楚。 是java
valen_jia 2009-05-12
  • 打赏
  • 举报
回复
js or java?

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧