Java_ABC_6.解析XML

package xml;

import org.w3c.dom.*;
import javax.xml.parsers.*;

public class XmlParser
{
private Document document = null;
/**
* 初始化XML文件对象
*
* @param xmlFile
* @throws Exception
*/
private void init(String xmlFile) throws Exception
{
//1. 建立一个解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//2. 利用工厂来获得一个具体解析对象
DocumentBuilder db = dbf.newDocumentBuilder();
//3. .Parse()接受一个XML文档名作为参数,返回Document对象,代表了一个XML文档的树结构
document = db.parse(xmlFile);
}

/**
* 解析XML文件内容
*
* @param xmlFile
* @throws Exception
*/
public void parseXML(String xmlFile) throws Exception
{
this.init(xmlFile);

//XML文件中只有一个根节点,把根节点拿出来
Element element = document.getDocumentElement();
//输出根节点的名称
System.out.println("根元素为:" + element.getTagName());

//person节点链的长度,二级标签candidate->person,节点链中存储单元为person标记的数据
NodeList nodeList =document.getElementsByTagName("person");
System.out.println("person节点链的长度:" + nodeList.getLength());

for(int m = 0; m != nodeList.getLength(); m++)
{
// 读取person链中第m个节点,输出节点名称
Node fatherNode = nodeList.item(m);
System.out.println("父节点名称:" + fatherNode.getNodeName());

// 读取父节点的属性 <person name = "wltao" id = "1">
NamedNodeMap attributes = fatherNode.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
Node attribute = attributes.item(i);
System.out.println("person的属性名为:" + attribute.getNodeName()
+ "对应的属性值为:" + attribute.getNodeValue());
}

//建立父节点的子节点链表
NodeList childNodes = fatherNode.getChildNodes();
System.out.println(childNodes.getLength());

//读取子节点链表
for (int j = 0; j < childNodes.getLength(); j++)
{
Node childNode = childNodes.item(j);
// 如果这个节点属于Element,再进行取值
if (childNode instanceof Element)
{
System.out.println("子节点名为:" + childNode.getNodeName()
+ "对应相应值为:" + childNode.getFirstChild().getNodeValue());
}
}
System.out.println("");
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值