3.2XML中的XPath和XML、对象之间的转换

(XPath、XMl和对象之间的转换)

1、XPath的介绍

XPath 是一门在 XML 文档中查找信息的语言。类似于数据库的SQL。

XPath 是通过元素和属性进行查找

XPath简化了Dom4j查找节点的过程
使用XPath必须导入jaxen-1.1-beta-6.jar
否则出现NoClassDefFoundError: org/jaxen/JaxenException

2、Xpath语法:

3、XPath进行信息查询的代码:


package com.test;

import java.io.File;
import java.util.List;

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

public class TestXPath {
	public static void main(String[] args) {

		File xmlFile = new File(
				"D:\\WorkSpace6.5\\java1603\\Eclipse\\Xml_Project\\src\\student.xml");

		SAXReader saxReader = new SAXReader();
		String xpath = "";
		List<Element> stuList = null;
		Element element = null;
		try {
			Document document = saxReader.read(xmlFile);
			Element root = document.getRootElement();
			/**
			 * 1:通过XPath来查找节点
			 */
			// 1:查找XML所有的student
			xpath = "/root/student";
			stuList = document.selectNodes(xpath);
			System.out.println(stuList.size());

			/**
			 * 2:使用相对路径,从root来查询
			 */
			stuList = root.selectNodes("student");
			System.out.println(stuList.size());
			/**
			 * 3:获取所有name为student元素对象,不考虑位置
			 */
			stuList = document.selectNodes("//student");
			System.out.println(stuList.size());

			// 2:查询sudent元素中id = 4的元素节点
			element = (Element) document.selectSingleNode("//student[@id='4']");
			System.out.println(element.attributeValue("id"));

			// 3:查询性别为男的元素节点
			stuList = document.selectNodes("/root/student[stu_sex='男']");
			System.out.println(stuList.size());
			// 4:查询名称中包含"a"的元素节点,类似like语句。
			stuList = document
					.selectNodes("/root/student[contains(stu_name,'a')]");
			System.out.println(stuList.size());

			// 4:查询名称中包含"a"的元素节点,或者年龄大于20岁
			stuList = document
					.selectNodes("/root/student[contains(stu_name,'a') or stu_age>=20]");
			System.out.println(stuList.size());
			// 4:查询名称中包含"a"的元素节点,并且年龄大于20岁
			stuList = document
					.selectNodes("/root/student[contains(stu_name,'a')][stu_age>=20]");
			System.out.println(stuList.size());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

4、XMl与对象之间的转换

   XStream对象相当Java对象和XML之间的转换器,转换过程是双向的。创建XSteam对象的方式很简单,只需要new XStream()即可。

              Java到xml,用toXML()方法。  
              Xml到Java,用fromXML()方法。 

 在没有任何设置默认情况下,java到xml的映射,是java成员名对应xml的元素名,java类的全名对应xml根元素的名字。而实际中,往往是xml和java类都有了,要完成相互转换,必须进行别名映射。
别名配置包含三种情况: 
 1、类别名,用alias(String name, Class type)。 
 2、类成员别名,用aliasField(String alias, Class definedIn, String fieldName) 
 3、类成员作为属性别名,用 aliasAttribute(Class definedIn, String attributeName, String alias)

package com.test;

import java.io.FileOutputStream;

import com.bean.StudentBean;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 * XML与Java对象之间的转换
 * 
 * @author ctd
 *
 */
public class XmlToJava {
	public static void main(String[] args) {
		XmlToJava.objectToXML();

		// XmlToJava.xmlToObject();
	}

	private static void objectToXML() {
		StudentBean student = new StudentBean();
		student.setStu_id(1);
		student.setStu_name("admin");
		student.setStu_sex("男");
		student.setStu_content("备注内容");
		student.setStu_age(20);

		/**
		 * 将对象转为XML字符串/XML文件
		 * 
		 * 1:通过字符串的拼接
		 * 
		 * 2:通过X-Stream对象来进行转换,得包含xstream-1.4.5.jar
		 */
		/**
		 * 解决下划线的问题
		 */
		XStream stream = new XStream(new XppDriver(new XmlFriendlyNameCoder(
				"_-", "_")));
		/**
		 * 更改根节点的名称
		 */
		stream.alias("root", StudentBean.class);
		/**
		 * 将id做为属性
		 */
		stream.aliasAttribute(StudentBean.class, "stu_id", "id");
		System.out.println(stream.toXML(student));

		/**
		 * 生成一个文件
		 */
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(
					"E:\\test.xml");
			fileOutputStream.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
					.getBytes());
			fileOutputStream.write("\n".getBytes());
			stream.toXML(student, fileOutputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void xmlToObject() {
		XStream stream = new XStream(new DomDriver());
		stream.alias("root", StudentBean.class);
		stream.aliasAttribute(StudentBean.class, "stu_id", "id");

		StringBuffer xml = new StringBuffer();
		xml.append("<root id='2'>");
		xml.append("  <stu_name>admin</stu_name>");
		xml.append("  <stu_sex>男</stu_sex>");
		xml.append("  <stu_age>20</stu_age>");
		xml.append("  <stu_content>备注内容</stu_content>");
		xml.append("</root>");
		StudentBean studentBean = (StudentBean) stream.fromXML(xml.toString());

		System.out.println(studentBean.getStu_id() + "\t"
				+ studentBean.getStu_name());
	}
}
studentBean.java

package com.bean;

public class StudentBean {
	private int stu_id;
	private String stu_name;
	private String stu_sex;
	private int stu_age;
	private String stu_content;

	public int getStu_id() {
		return stu_id;
	}

	public void setStu_id(int stu_id) {
		this.stu_id = stu_id;
	}

	public String getStu_name() {
		return stu_name;
	}

	public void setStu_name(String stu_name) {
		this.stu_name = stu_name;
	}

	public String getStu_sex() {
		return stu_sex;
	}

	public void setStu_sex(String stu_sex) {
		this.stu_sex = stu_sex;
	}

	public int getStu_age() {
		return stu_age;
	}

	public void setStu_age(int stu_age) {
		this.stu_age = stu_age;
	}

	public String getStu_content() {
		return stu_content;
	}

	public void setStu_content(String stu_content) {
		this.stu_content = stu_content;
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java获取XML数据的所有XPath路径可以使用递归方法来实现,遍历XML节点并存储XPath路径。以下是一个示例代码: ```java import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.util.ArrayList; import java.util.List; public class XpathExtractor { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("path/to/xml/file.xml"); List<String> xpaths = getXPaths(doc); for (String xpath : xpaths) { System.out.println(xpath); } } public static List<String> getXPaths(Node node) throws Exception { List<String> xpaths = new ArrayList<>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); // 获取节点的XPath XPathExpression xpathExp = xpath.compile(getNodeXPath(node)); String xpathValue = (String) xpathExp.evaluate(node, XPathConstants.STRING); xpaths.add(xpathValue); // 遍历子节点 NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { xpaths.addAll(getXPaths(child)); } } return xpaths; } private static String getNodeXPath(Node node) { StringBuilder builder = new StringBuilder(); for (; node != null; node = node.getParentNode()) { int index = getNodeIndex(node); String nodeName = node.getNodeName(); builder.insert(0, "/" + nodeName + "[" + index + "]"); } return builder.toString(); } private static int getNodeIndex(Node node) { int index = 1; for (Node sibling = node.getPreviousSibling(); sibling != null; sibling = sibling.getPreviousSibling()) { if (sibling.getNodeType() == node.getNodeType() && sibling.getNodeName().equals(node.getNodeName())) { index++; } } return index; } } ``` 该示例代码使用了递归方法来获取XML数据的所有XPath路径。getXPaths()方法接收一个XML节点,将该节点的XPath路径添加到一个列表,并递归遍历节点的子节点,直到所有节点都被遍历完为止。该示例代码还包括了getNodeXPath()和getNodeIndex()方法,用于获取节点的XPath路径和节点的索引。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值