使用dom解析xml

这里是一个根据xml数据定时上传数据的案例,每天抽取三条信息随机发送给不同的三个用户,然后随机发送账户给不同的三个交易团队,这里用到了quartz。


下面是xml的整体结构和部分模拟数据

<?xml version="1.0" encoding="UTF-8" ?>

<Accounts>     
    <Account id="1">      
        <openUser>王先生</openUser><!-- 开户姓名 -->     
        <openEquity>中泰证券</openEquity><!-- 开户劵商 -->     
        <salesDept>暂无</salesDept><!-- 营业部 -->      
        <capitalAccount>xxxxxx</capitalAccount><!-- 资金账户 -->
        <capitalPassword>ODg4ODg4</capitalPassword><!-- 交易密码888888 -->
        <accountType>1</accountType><!-- 普通账户 -->
        <profitModel>0</profitModel><!-- 稳定收益 -->
        <available>0.00</available><!-- 初始可用市值 -->
        <availableSplit>我要40%</availableSplit><!-- 年化可用分成 -->
        <ableMoney>0.00</ableMoney><!-- 可用资金 -->
        <commission>万2.5</commission><!-- 佣金 -->
        <profitConfig>0.00</profitConfig><!-- 收益分配 -->
        <message>寻找日内交易团队</message><!-- 留言 -->
        <isPayMargin>0</isPayMargin><!-- 是否缴纳保证金(使用过后标记为1) -->
        <Shares>
        	<share>
        		<name>恒生电子</name>
        		<code>600570</code>
        		<number>25800</number>
        	</share>
        	<share>
        		<name>金证股份</name>
        		<code>600446</code>
        		<number>18500</number>
        	</share>
        </Shares>
    </Account> 
    
    <Account id="2">      
        <openUser>王先生</openUser><!-- 开户姓名 -->     
        <openEquity>银河证券</openEquity><!-- 开户劵商 -->     
        <salesDept>暂无</salesDept><!-- 营业部 -->      
        <capitalAccount>xxxxx</capitalAccount><!-- 资金账户 -->
        <capitalPassword>ODg4ODg4</capitalPassword><!-- 交易密码888888 -->
        <accountType>1</accountType><!-- 普通账户 -->
        <profitModel>0</profitModel><!-- 稳定收益 -->
        <available>0.00</available><!-- 初始可用市值 -->
        <availableSplit>我要40%</availableSplit><!-- 年化可用分成 -->
        <ableMoney>0.00</ableMoney><!-- 可用资金 -->
        <commission>万2.5</commission><!-- 佣金 -->
        <profitConfig>0.00</profitConfig><!-- 收益分配 -->
        <message>找一个靠谱的交易团队合作</message><!-- 留言 -->
        <isPayMargin>0</isPayMargin><!-- 是否缴纳保证金(使用过后标记为1) -->
        <Shares>
        	<share>
        		<name>汇金股份</name>
        		<code>300368</code>
        		<number>34000</number>
        	</share>
        	<share>
        		<name>同花顺</name>
        		<code>300033</code>
        		<number>29000</number>
        	</share>
        </Shares>
    </Account> 
    
    <Account id="3">      
        <openUser>王先生</openUser><!-- 开户姓名 -->     
        <openEquity>光大证券</openEquity><!-- 开户劵商 -->     
        <salesDept>暂无</salesDept><!-- 营业部 -->      
        <capitalAccount>xxxxxx</capitalAccount><!-- 资金账户 -->
        <capitalPassword>ODg4ODg4</capitalPassword><!-- 交易密码888888 -->
        <accountType>1</accountType><!-- 普通账户 -->
        <profitModel>0</profitModel><!-- 稳定收益 -->
        <available>0.00</available><!-- 初始可用市值 -->
        <availableSplit>我要40%</availableSplit><!-- 年化可用分成 -->
        <ableMoney>0.00</ableMoney><!-- 可用资金 -->
        <commission>万2.5</commission><!-- 佣金 -->
        <profitConfig>0.00</profitConfig><!-- 收益分配 -->
        <message>日内交易供券</message><!-- 留言 -->
        <isPayMargin>0</isPayMargin><!-- 是否缴纳保证金(使用过后标记为1) -->
        <Shares>
        	<share>
        		<name>东方财富</name>
        		<code>300059</code>
        		<number>70000</number>
        	</share>
        	<share>
        		<name>中科金财</name>
        		<code>002657</code>
        		<number>33000</number>
        	</share>
        </Shares>
    </Account> 
</Accounts>

工具类

package com.hongwei.futures.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @description 读取xml配置文件信息
 * @author qyq
 */
public class XmlUtil {

	/**
	 * WebRoot目录的绝对路径
	 * 
	 * @return
	 */
	public static String getWebRootAbsolutePath() {
		String path = null;
		String folderPath = XmlUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		if (folderPath.indexOf("WEB-INF") > 0) {
			path = folderPath.substring(0, folderPath.indexOf("WEB-INF/classes"));
		}
		return path;
	}

	/**
	 * 获取Document对象
	 * 
	 * @return
	 */
	public static Document getDocument(String xmlPath) {
		Document document = null;
		try {
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			FileInputStream inputStream = new FileInputStream(new File(xmlPath));
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			document = builder.parse(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return document;
	}

	/**
	 * 根据xml路径返回xml文件集合
	 * 
	 * @param xmlPath
	 * @return
	 */
	public static NodeList getNodeList(String xmlPath, String tagName) {
		// 首先我们需要通过DocumentBuilderFactory获取xml文件的工厂实例。
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setIgnoringElementContentWhitespace(true);
		NodeList sonlist = null;
		try {
			// 创建文档对象
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(xmlPath); // 使用dom解析xml文件
			sonlist = doc.getElementsByTagName(tagName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sonlist;
	}

	/**
	 * 获取目标节点,进行修改,完成后,保存文件。
	 * 
	 * @param express
	 * @param source
	 * @return
	 */
	public static void updateNode(Document document, String xmlPath, String parentTag, String attribute, String attrValue, String sonTag, String sonValue) {
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName(parentTag);

		for (int i = 0; i < nodeList.getLength(); i++) {
			Element element = (Element) nodeList.item(i);
			if (element.getAttribute(attribute).equals(attrValue)) {
				NodeList sonList = element.getChildNodes();

				for (int j = 0; j < sonList.getLength(); j++) {
					if (sonList.item(j) instanceof Node) {
						Node sonNode = sonList.item(j);
						if (sonNode.getNodeName().equals(sonTag)) {
							sonNode.setTextContent(sonValue);
						}
					}
				}
			}
		}
		saveXml(document, xmlPath);
	}

	/**
	 * 根据目标节点属性值删除节点,完成后,保存文件。
	 * 
	 * @param express
	 * @param xmlPath
	 */
	public static void delNode(Document document, String xmlPath, String tagName, String attribute, String attrValue) {
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName(tagName);
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node.getAttributes().getNamedItem(attribute).getNodeValue().equals(attrValue)) {
				node.getParentNode().removeChild(node);
			}
		}
		saveXml(document, xmlPath);
	}

	/**
	 * 保存xml文件
	 */
	public static void saveXml(Document document, String xmlPath) {
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource domSource = new DOMSource(document);
			FileOutputStream outputStream = new FileOutputStream(new File(xmlPath));
			StreamResult streamResult = new StreamResult(outputStream);
			transformer.transform(domSource, streamResult);
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

定时任务类

package com.hongwei.futures.task;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.hongwei.futures.model.FuStockAccount;
import com.hongwei.futures.model.FuTransaction;
import com.hongwei.futures.model.FuUser;
import com.hongwei.futures.model.StockShare;
import com.hongwei.futures.service.FuStockAccountService;
import com.hongwei.futures.service.FuTransactionService;
import com.hongwei.futures.service.FuUserService;
import com.hongwei.futures.service.StockShareService;
import com.hongwei.futures.util.XmlUtil;

public class SendStockUtil extends TimerTask {
	@Autowired
	private FuStockAccountService fuStockAccountService;
	@Autowired
	private FuUserService fuUserService;
	@Autowired
	private FuTransactionService fuTransactionService;
	@Autowired
	private StockShareService stockShareService;

	private Object lock = new Object();
	private volatile boolean isRunning = false;

	/**
	 * 定期发劵
	 */
	@Override
	public void run() {
		synchronized (lock) {
			if (isRunning) {
				return;
			}
			isRunning = true;
			String xmlPath = XmlUtil.getWebRootAbsolutePath() + "uploads/xml/stockAccount.xml";
			List<FuUser> users = fuUserService.findAllUsers();
			List<FuTransaction> transactions = fuTransactionService.findAllTrans();

			int k = 0;
			NodeList nodeList = XmlUtil.getNodeList(xmlPath, "Account");
			if (nodeList != null && nodeList.getLength() > 0) {
				for (int i = 0; i < nodeList.getLength(); i++) {
					if (k >= 3) {// 只抽取三个劵发送出去
						break;
					}
					Element fatherNode = (Element) nodeList.item(i);// 父节点Account
					String fatherId = fatherNode.getAttributes().item(0).getNodeValue();// 父节点id属性值

					NodeList childNodes = fatherNode.getChildNodes();
					String childName = "";
					String childValue = "";
					for (int j = 0; j < childNodes.getLength(); j++) {
						Node childNode = childNodes.item(j);
						childName = childNode.getNodeName();// 子节点名称
						if (childName.equals("isPayMargin") && childNode instanceof Element) {
							childValue = childNode.getFirstChild().getNodeValue();// 子节点值
							break;
						}
					}
					// 没有缴纳保证金代表还没有发出去,可以发劵
					if (childName.equals("isPayMargin") && childValue.equals("0")) {
						System.out.println("发劵任务fatherId =" + fatherId);
						// 取当前父节点里的子节点值添加到股票表
						int userIndex = new Random().nextInt(users.size() - 1);
						int tranIndex = new Random().nextInt(transactions.size() - 1);
						FuStockAccount account = new FuStockAccount();
						account.setFuUser(users.get(userIndex));
						account.setTransactionId(transactions.get(tranIndex).getId());
						account.setOpenUser(fatherNode.getElementsByTagName("openUser").item(0).getTextContent());
						account.setOpenEquity(fatherNode.getElementsByTagName("openEquity").item(0).getTextContent());
						account.setSalesDept(fatherNode.getElementsByTagName("salesDept").item(0).getTextContent());
						account.setCapitalAccount(fatherNode.getElementsByTagName("capitalAccount").item(0).getTextContent());
						account.setCapitalPassword(fatherNode.getElementsByTagName("capitalPassword").item(0).getTextContent());
						account.setAccountType(Integer.valueOf(fatherNode.getElementsByTagName("accountType").item(0).getTextContent()));
						account.setCreateTime(new Date());
						account.setState(0);// 开启委托
						account.setIsDel(0);// 未删除
						account.setExamineStatus(4);// 接单成功
						account.setProfitModel(Integer.parseInt(fatherNode.getElementsByTagName("profitModel").item(0).getTextContent()));
						account.setAvailable(new BigDecimal(fatherNode.getElementsByTagName("available").item(0).getTextContent()));
						account.setAvailableSplit(fatherNode.getElementsByTagName("availableSplit").item(0).getTextContent());
						account.setAbleMoney(new BigDecimal(fatherNode.getElementsByTagName("ableMoney").item(0).getTextContent()));
						// account.setAbleMoneySplit(fatherNode.getElementsByTagName("ableMoneySplit").item(0).getTextContent());
						account.setTransactionStatus(0);// 未退劵
						account.setCommission(fatherNode.getElementsByTagName("commission").item(0).getTextContent());
						account.setOrderTime(new Date());
						account.setIsPublish(1);// 已发布
						account.setSourceType(0);// 网站
						account.setProfitConfig(new BigDecimal(fatherNode.getElementsByTagName("profitConfig").item(0).getTextContent()));
						account.setMessage(fatherNode.getElementsByTagName("message").item(0).getTextContent());
						account.setIsPayMargin(1);// 已缴纳保证金,不会再次发此券
						fuStockAccountService.save(account);

						// 把对应的股票信息添加到股票表
						for (int m = 0; m < childNodes.getLength(); m++) {
							Node shares = childNodes.item(m);
							if (shares.getNodeType() == Node.ELEMENT_NODE && shares.getNodeName().equals("Shares")) {// 得到Shares节点对象
								NodeList shareChild = shares.getChildNodes();// 得到share节点对象数组
								for (int n = 0; n < shareChild.getLength(); n++) {
									if (shareChild.item(n) instanceof Element) {
										Element shareNode = (Element) shareChild.item(n);// 得到share对象
										StockShare share = new StockShare();
										share.setFuStockAccount(account);
										share.setName(shareNode.getElementsByTagName("name").item(0).getTextContent());
										share.setCode(shareNode.getElementsByTagName("code").item(0).getTextContent());
										share.setNumber(Integer.valueOf(shareNode.getElementsByTagName("number").item(0).getTextContent()));
										stockShareService.save(share);
									}
								}
							}
						}
						users.remove(userIndex);// 从数组移除,避免重复发劵
						transactions.remove(tranIndex);// 从数组移除,避免重复派劵

						// 修改对应id父节点的指定名称子节点的值
						XmlUtil.updateNode(XmlUtil.getDocument(xmlPath), xmlPath, "Account", "id", fatherId, "isPayMargin", "1");
						k = k + 1;
					} else {
						continue;
					}
				}
			}
			isRunning = false;
		}
	}

}

定时任务的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
				http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
				http://www.springframework.org/schema/aop 
				http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
				http://www.springframework.org/schema/tx 
				http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
				http://www.springframework.org/schema/context 
				http://www.springframework.org/schema/context/spring-context-3.0.xsd
				">
	
	<!-- 定时发劵派劵 -->
	<bean id="SendStockUtil" class="com.hongwei.futures.task.SendStockUtil"></bean>
	<bean id="SendStockManager" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="SendStockUtil"/>
		<property name="targetMethod" value="run"/>
	</bean>
	<bean id="SendStockManagerTimer" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail" ref="SendStockManager"/>
		<property name="cronExpression" value="0 0 10,14 * * ?"/>
	</bean>
	
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="SendStockManagerTimer"/>
			</list>
		</property>
		<property name="quartzProperties">
            <map><entry key="org.quartz.threadPool.threadCount" value="1"/></map>
        </property>
	</bean>
</beans>
这样就实现了每天10点和14点定时读取xml文件的数据并上传到数据库。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值