使用DOM4J和xpath解析XML(二)
在使用Dom4j解析xml文档时,我们很希望有一种类似正则表达式的东西来规范查询条件,而xpath正是这样一种很便利的规则吧.
以下是本人用写的一个类,摘取部分代码;
Java代码
Java代码
String xmlName = path + "/" + userName + ".xml";
// 定义需要返回的第一级菜单的名字集合
List firstNames = new ArrayList();
// Attribute的属性集合
List attrs = new ArrayList();
// 声明SAXReader
SAXReader saxReader = new SAXReader();
try {
Document doc = saxReader.read(xmlName);
// 获得所有grade=1的Element的text的值
String xpath = "/tree/item";
List list = doc.selectNodes(xpath);
Iterator it = list.iterator();
while (it.hasNext
相关文档:
第一种方式--使用MSXML2.DOMDOCUMENT.4.0
创建xmldoc对象,并装载一个xml
Set xmldoc = CreateObject("MSXML2.DOMDOCUMENT.4.0")
xmldoc.loadXML ("一个具体的XML实体")
选择需要筛选的结点
Set nodeList = xmldoc.selectNodes("//*[count(ancestor::*)= 2]") '根节点的第二代后代
Set nodeList = xmldoc ......
java 代码
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList; ......
// TestXml.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include "tinyxml.h"
#include "lang.h"
#include <string>
using namespace std;
using namespace std;
#pragma comment(lib, "tinyxmld.lib")
B ......
private XmlDocument xmlDoc;
private void btnCreateXml_Click(object sender, EventArgs e)
{
//自 ......
1、首先下载 xstream.jar和jettison.jar(转换为json时用到),并引入该包。
2、看如下代码吧:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import c ......