#SQL语法
一、Dom4j解析(需要导入Dom4j.jar):
import java.io.FileOutputStream;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jUtil {
private static final String DEFAULT_PATH = "src/com/cuncaojin/xmlFile.xml";
private Dom4jUtil() {
}
public static Document getDocument(String filePath) throws DocumentException {
SAXReader saxReader = new SAXReader();
filePath = filePath == null ? DEFAULT_PATH : filePath;
return saxReader.read(filePath);
}
public void write2XML(Document document, String filePath) throws IOException {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
filePath = filePath == null ? DEFAULT_PATH : filePath;
XMLWriter writer = new XMLWriter(new FileOutputStream(filePath), format);
writer.write(document);
writer.close();
}
}
二、XPath解析(依赖Dom4j解析技术,需要导入Dom4j.jar和jaxen-1.1-beta-6.jar包):
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Demo {
public static void main(java.lang.String[] args) throws Exception {
String path = "myxml.xml";
Document document = new SAXReader().read(path);
List<Element> selectNodes = document.selectNodes("//addr[@id='addrs']");
// List<Element> selectNodes = document.selectNodes("//addr");
for (Node node : selectNodes) {
System.out.println(node.getText());
}
}
}
1、结合Dom4j获取Document对象(XPath解析技术依赖Dom4j解析技术)
2、导入Dom4j.jar和jaxen-1.1-beta-6.jar
3、如果想使用XPATH语言,条件:只能使用node节点对象中的两个方法:
List selectNodes(String xpathExpression);
Node selectSingleNode(String xpathExpression);
4、xpathExpression的写法,查文档