㈠ JAVA 如何獲取並替換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>
2. java實現實例:
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);
}
3. 測試
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));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
測試結果:
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
㈡ java過濾非法字元的filter
filter代碼在pujia12345提供的代碼上改的;
jsp頁面的編碼你設成你自己的,我用的是-8。
input.jsp輸入後,正常跳轉到handle.jsp,而禁詞已經被過濾。
filter:
package test;
import java.io.*;
import javax.servlet.*;
import java.util.*;
public class MyFilter implements Filter
{
private List<String> unString;
public void init(FilterConfig filterConfig) throws ServletException
{
unString = new ArrayList<String>();
unString.add("日");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
String content = request.getParameter("content");//需要過濾的參數
if(content!=null){
for (int i = 0; i < unString.size(); i++)
{
String strIllegal = unString.get(i);
if (content.indexOf(strIllegal) >= 0)
{
content = content.replaceAll(strIllegal, "");//非法字元替換成空
}
request.setAttribute("content", content);//為request設置屬性保存修改後的值
}
}
chain.doFilter(request, response);
}
public void destroy()
{
//System.out.println("過濾器銷毀");
}
}
//---------------------------//
web.xml:
<filter>
<filter-name>myfilter</filter-name>
<filter-class>test.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
//---------------------------//
輸入頁面input.jsp:
<%@page contentType="text/html;charset=utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>input.jsp</title>
</head>
<body>
<form action="handle.jsp" method="post">
<input type="text" name="content" />
<input type="submit" value=" 提交 " />
</form>
</body>
</html>
//---------------------------//
input提交的頁面handle.jsp:
<%@page contentType="text/html;charset=utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> handle.jsp </title>
</head>
<body>
<%
String content = (String)request.getAttribute("content");
out.println(content);
%>
</body>
</html>
㈢ java分割xml類型的字元串
public static void main(String[] args) {
String xml="<response>" +
"<head>" +
"<code>0</code>" +
"<message></message>" +
"</head>" +
"<body>" +
"<test>" +
"<no>1</no>" +
"<addr>123</addr>" +
"</test>" +
"<test>" +
"<no>2</no>" +
"<addr>124</addr>" +
"</test>" +
"</body>" +
"</response>";
try {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
List<Element> dataList = root
.selectNodes("//body/test");
for (Element e2 : dataList) {
String no=e2.elementText("no");
String addr=e2.elementText("addr");
System.out.println(no+" "+addr);
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
需要這個dom4j-1.6.1.jar
㈣ java 去除xml字元串里有null的節點 求大神
publicclassRemoveNullElement{
publicstaticvoidmain(String[]args){
Stringxml="<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?><A><id>null</id><name>李三</name><id><id>null</id><name>李三</name><id>null</id></id></A>";
try{
Documentdoc=DocumentHelper.parseText(xml);
newRemoveNullElement().removeNullElement(doc.getRootElement(),doc.getRootElement());
System.out.println(doc.asXML());
}catch(DocumentExceptione){
System.out.println("parsexmlfailed!"+e);
e.printStackTrace();
}
}
privatevoidremoveNullElement(Elementele,Elementparent){
if(ele==null){
return;
}
if(ele.getText()!=null&&ele.getText().equalsIgnoreCase("null")){
parent.remove(ele);
}else{
List<Element>children=ele.elements();
if(children!=null&&children.size()>0){
for(Elementchild:children){
removeNullElement(child,ele);
}
}
}
}
}
寫了個刪除null節點的方法,遞歸調用。
㈤ java 截取 xml(字元串)的子節點
你好,直接indexOf <task> 跟 </task> 然後subString一下都沒問題.
或者正則表達式
<task>(.*?)</task>
如果是一個長期的工程,量比較大的,考慮用dom4j來做吧.
http://xhy0422.iteye.com/blog/50235
對於已經是字元串的xml,可以
㈥ XML 解析中,如何排除控制字元
package com.huayu;
import Java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class Test3 {
public static void main(String []args){
try {
//1.創建一個工廠
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
//2.得到解析器
DocumentBuilder db=dbf.newDocumentBuilder();
//3.//字元串
String strTest="<?xml version=/"1.0/" encoding=/"gb2312/"?>"
+"<company>"
+"<person sex=/"male/">"
+"<name>小三子</name>"
+"<email>[email protected]</email>"
+"</person>"
+"<person sex=/"male/">"
+"<name>小三子</name>"
+"<email>[email protected]</email>"
+"</person>"
+"<person sex=/"male/">"
+"<name>小三子</name>"
+"<email>[email protected]</email>"
+"</person>"
+"</company>";
//在編程中,字元串從網路傳遞
InputStream is=new ByteArrayInputStream(strTest.getBytes());
Document dm=db.parse(is);
NodeList nl=dm.getElementsByTagName("person");
//5.改進將 Node 換成 Element (Element提供了更加豐富的方法,解決不能指定得到某個子節點的問題)
//得到第一個人的信息
Element el=(Element)nl.item(0);
//指定得到某個子節點
NodeList nll=el.getElementsByTagName("email");
//列印name值,這是固定的取法
String name=((Element)nll.item(0)).getFirstChild().getNodeValue();
System.out.println("email="+name);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
㈦ java截取XML字元串
indexOf("<")
indexOf(">")
subString
㈧ java解析第三方xml文件 文件中的特殊字元如何處理 文件不可改
一般的特殊字元都是需要轉義的,請參閱xml特殊字元如何轉義。
㈨ 在Java程序處理中,對於XML格式的字元串,碰到&,『,「等字元,該如何處理
& 是用 & a m p ; 來代替
去掉空格……昨天寫完忘記看被自己換成&了
引號不記得了
差不多的方法,自己查查吧
㈩ java過濾特殊字元的問題
"+"在URL中會被當作空格處理。
必須使用URLEncoder將其變成URL編碼。
或者使用 javascript 的 encodeURIComponent(url) 函數對URL進行編碼轉換。