String与XML互转以及从XML取节点值并修改

  • 读取xml文件生成Document对象
  • Document转换成String类型串
  • String串转成xml
  • 已知xml节点取节点值
  • 已知xml节点修改节点值

一个xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<transaction>
	<body>
		<request>
			<tranTyp>批量业务现存</tranTyp>
			<acctNm>0085213560</acctNm>
			<acctNo>6225885517843413</acctNo>
			<avlBal>201958.65</avlBal>
			<acctTyp>0</acctTyp>
			<tranTime>20170801101030</tranTime>
			<currencyTyp>CNY</currencyTyp>
			<tranDesc></tranDesc>
			<bal>201958.65</bal>
			<tranAmt>100000.00</tranAmt>
		</request>
	</body>
	<header>
		<msg>
			<sndTm>101019</sndTm>
			<msgCd>WCS0000200</msgCd>
			<seqNb>632376531000009</seqNb>
			<sndMbrCd>5200</sndMbrCd>
			<rcvMbrCd>0000</rcvMbrCd>
			<sndDt>20170821</sndDt>
			<sndAppCd>CBS</sndAppCd>
			<rcvAppCd>WCS</rcvAppCd>
			<callTyp>SYN</callTyp>
		</msg>
		<ver>1.0</ver>
		<pnt>
			<sndTm>101216</sndTm>
			<sndMbrCd>0000</sndMbrCd>
			<rcvMbrCd>0000</rcvMbrCd>
			<sndDt>20170809</sndDt>
			<sndAppCd>ESB</sndAppCd>
			<rcvAppCd>WCS</rcvAppCd>
		</pnt>
	</header>
</transaction>

java实现实例:

package com.adtec.mq.client;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

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

public class Test {

	/**
	 * 
	 * @param document
	 *            Document对象(读xml生成的)
	 * @return String字符串
	 * @throws Throwable
	 */
	public String xmlToString(Document document) throws Throwable {
		TransformerFactory ft = TransformerFactory.newInstance();
		Transformer ff = ft.newTransformer();
		ff.setOutputProperty("encoding", "GB2312");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ff.transform(new DOMSource(document), new StreamResult(bos));
		return bos.toString();
	}

	/**
	 * 
	 * @param xml形状的str串
	 * @return Document 对象
	 */
	public Document StringTOXml(String str) {

		StringBuilder sXML = new StringBuilder();
		sXML.append(str);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document doc = null;
		try {
			InputStream is = new ByteArrayInputStream(sXML.toString().getBytes("utf-8"));
			doc = dbf.newDocumentBuilder().parse(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}

	/**
	 * 
	 * @param document
	 * @return 某个节点的值 前提是需要知道xml格式,知道需要取的节点相对根节点所在位置
	 */
	public String getNodeValue(Document document, String nodePaht) {
		XPathFactory xpfactory = XPathFactory.newInstance();
		XPath path = xpfactory.newXPath();
		String servInitrBrch = "";
		try {
			servInitrBrch = path.evaluate(nodePaht, document);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return servInitrBrch;
	}

	/**
	 * 
	 * @param document
	 * @param nodePath
	 *            需要修改的节点相对根节点所在位置
	 * @param vodeValue
	 *            替换的值
	 */
	public void setNodeValue(Document document, String nodePath, String vodeValue) {
		XPathFactory xpfactory = XPathFactory.newInstance();
		XPath path = xpfactory.newXPath();
		Node node = null;
		;
		try {
			node = (Node) path.evaluate(nodePath, document, XPathConstants.NODE);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		node.setTextContent(vodeValue);
	}

	public static void main(String[] args) throws Throwable {
		// 读取xml文件,生成document对象
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		// 文件的位置在工作空间的根目录(位置随意,只要写对就ok)
		Document document = builder.parse(new File("a.xml"));

		Test t = new Test();
		// XML————》String
		String str = t.xmlToString(document);
		System.out.println("str:" + str);
		// String ————》XML
		Document doc = t.StringTOXml(str);
		String nodePath = "/transaction/header/msg/sndMbrCd";
		// getNodeValue
		String nodeValue = t.getNodeValue(doc, nodePath);
		System.out.println("修改前nodeValue:" + nodeValue);
		// setNodeValue
		t.setNodeValue(doc, nodePath, nodeValue + "hello");
		System.out.println("修改后nodeValue:" + t.getNodeValue(doc, nodePath));
	}

}

测试结果:

str:<?xml version="1.0" encoding="UTF-8" standalone="no"?><transaction>
	<body>
		<request>
			<tranTyp>批量业务现存</tranTyp>
			<acctNm>0085213560</acctNm>
			<acctNo>6225885517843413</acctNo>
			<avlBal>201958.65</avlBal>
			<acctTyp>0</acctTyp>
			<tranTime>20170801101030</tranTime>
			<currencyTyp>CNY</currencyTyp>
			<tranDesc/>
			<bal>201958.65</bal>
			<tranAmt>100000.00</tranAmt>
		</request>
	</body>
	<header>
		<msg>
			<sndTm>101019</sndTm>
			<msgCd>WCS0000200</msgCd>
			<seqNb>632376531000009</seqNb>
			<sndMbrCd>5200</sndMbrCd>
			<rcvMbrCd>0000</rcvMbrCd>
			<sndDt>20170821</sndDt>
			<sndAppCd>CBS</sndAppCd>
			<rcvAppCd>WCS</rcvAppCd>
			<callTyp>SYN</callTyp>
		</msg>
		<ver>1.0</ver>
		<pnt>
			<sndTm>101216</sndTm>
			<sndMbrCd>0000</sndMbrCd>
			<rcvMbrCd>0000</rcvMbrCd>
			<sndDt>20170809</sndDt>
			<sndAppCd>ESB</sndAppCd>
			<rcvAppCd>WCS</rcvAppCd>
		</pnt>
	</header>
</transaction>
修改前nodeValue:5200
修改后nodeValue:5200hello

更多问题,欢迎加群讨论 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20190822141234180.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xlaXN1cmVfbGlmZQ==,size_16,color_FFFFFF,t_70)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值