版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wanggeying/article/details/82255692
———————————实现原理
xsd视图化,主要是根据xsd文档把内容翻译出来,可读性比较强。
xml编辑,支持自由编辑,核心步骤如下3步:
1、打开文件
2、操作文件(根据每个注释,进行信息更新处理。视图呈现也是以注释为核心)
3、保存文件
——————————–注意事项
1、注释不能重复,否则出现内存溢出等现象,size。indexof。
2、升级维护时注意:思路要清晰,里面用到有序的对象嵌套对象、迭代、注释为核心的阶段性处理
3、目前产品结果,文档语言视图化xml、自由编辑。结合实际xsd自测没问题,但是还没实际应用。
——————————-核心示例代码如下
jsp
<body>
<div class="col-sm-12" style="position:fixed;z-index: 1000;height:65px;border-bottom: 1px solid #337ab7;background-color: #f3f3f3;padding-top: 15px;">
<div class="col-sm-6 col-sm-offset-3">
<div class="pull-left search" style="margin: 0px 10px; position: relative;">
<select id="fileType" name="fileType" class="form-control" id="changeChooseAreaType" onchange="getFileName();">
<option value="0">请选择文件类型</option>
<option value="1">1......xsd</option>
<option value="2">2......xsd</option>
<option value="3">3......xsd</option>
<option value="4">4......xsd</option>
<option value="5">5......xsd</option>
<option value="6">6......xsd</option>
<option value="7">7......xsd</option>
<option value="8">8......xsd</option>
<option value="9">9......xsd</option>
<select>
</div>
<div class="pull-left search" style="margin: 0px 10px; position: relative;">
<select id="bwName" name="bwName" class="form-control" id="changeChooseAreaType">
<option value="0">请选择报文名称</option>
<select>
</div>
<button type="button" onclick="qd();" class="btn btn-primary dropdown-toggle"><span class="fa fa-th-list fa-fw"></span>确定</button>
</div>
</div>
<div class="search col-sm-12" style="margin: 80px 10px 50px 20px; position: relative;" id="content" name="content"></div>
</body>
js
/**
* 初始化
*/
var currentProjectPath='';
$(function() {
//获取当前路径
currentProjectPath = window.document.location.href.substring(0, window.document.location.href.indexOf(window.document.location.pathname ) )+ window.document.location.pathname.substring( 0, window.document.location.pathname.substr( 1 ).indexOf( '/' ) + 1 );
//初始化select下拉列表框
getFileName();
});
/**
* 确定按钮
*/
function qd(){
//获取报文名称
var bwname=$("#bwName ").val();
//清空数据
$('#content').html("");
//根据报文名称,检索报文内容
$.ajax({
type: 'POST',
data: {bwname:bwname},
url:currentProjectPath+"/schemeChange/readFileContent2.do",
dataType: "json",
crossDomain: true,
xhrFields: {
withCredentials: true
},
error: function(e) {},
success: function(datas) {
//声明对象
var groups='';
var comments;//注释
var name;//元素名称
var type;//元素类型
var value="";//元素接受值
var typeobj;//元素类型绑定对象
var valueobj;//元素接受值绑定对象
var str_min_max;
//赋值
var obj=datas.moreData.data;
var comments_pre="";
var commentscount=0;
for(var key in obj){
comments=key;//注释
comments_obj=obj[key];//对象
for(comments_obj_key in comments_obj){
if(comments_pre!="" && comments_pre==comments){
commentscount++;
}
child_strs="";
obj_key=comments_obj_key;//元素名称&元素值
obj_value=comments_obj[obj_key];
for(obj_value_key in obj_value){
attr_name=obj_value_key;//属性名称
attr_value=obj_value[obj_value_key];//属性值
if(attr_name=="restriction"){
child_strs=child_strs+"接受类型:<input type=\"text\" class=\"form-control\" name=\""+attr_name+"\" value="+attr_value+">";
}else if(attr_value!="" && attr_value.split(",").length>1){
var str="";
var n=0;
for(var i=0;i<attr_value.split(",").length;i++){
var str_value="<input type=\"text\" class=\"form-control\" name=\""+attr_name+"@"+attr_value.split(",")[i]+"\" value="+attr_value.split(",")[i]+">";
if(attr_name.split(",")[i]=="totalDigits"){
str=str+"最多小数位数:"+str_value;
} else if(attr_name.split(",")[i]=="fractionDigits"){
str=str+"数字最多位数:"+str_value;
} else if(attr_name.split(",")[i]=="minLength"){
str=str+"最小长度:"+str_value;
} else if(attr_name.split(",")[i]=="maxLength"){
str=str+"最大长度:"+str_value;
} else{
n++;
str=str+str_value;
}
}
if(n>1){
str="录入数据:"+str;
}
child_strs=child_strs+str;
}else{
child_strs=child_strs+"录入数据:<input type=\"text\" class=\"form-control\" name=\""+attr_name+"\" value="+attr_value+">";
}
console.log(child_strs);
}
var strs="";
if(obj_key.split("&")[0]=="element"){
var str="元素名称:<input type=\"text\" class=\"form-control\" name=\""+obj_key.split("&")[0]+"\" value="+obj_key.split("&")[1]+">"
strs=strs+str;
}
if(obj_key.split("&")[0]=="attribute"){
var str="属性名称:<input type=\"text\" class=\"form-control\" name=\""+obj_key.split("&")[0]+"\" value="+obj_key.split("&")[1]+">"
strs=strs+str;
}
if(commentscount>=1){
comments='';
}
var group="<div class=\"form-group col-sm-12\">" +
"<label for=\"firstname\" class=\"col-sm-3 control-label\">"+comments+"</label>" +
"<div class=\"col-sm-5\">" +
"<input type=\"hidden\" class=\"form-control\" name=\"comments\" value="+comments+">" +
strs+
child_strs+
"</div>" +
"</div>";
groups=groups+group;
comments_pre=comments;
}
}
var strs="<form id=\"xmlform\" name=\"xmlform\" class=\"form-horizontal form-content col-sm-12\" role=\"form\">" +
""+groups+"" +
"<div class=\"form-group b-save col-sm-12\">" +
"<div class=\"col-sm-offset-5 col-sm-9\">" +
"<button type=\"button\" class=\"btn btn-primary\" onclick=\"saveform();\">保存</button>" +
"<div>" +
"</div>" +
"</form>";
$("#content").append(strs);
}
});
}
function saveform(){
var formobj = $('#xmlform').serializeArray();
// console.log(formobj);
$.ajax({
type: 'POST',
data: {formobj:JSON.stringify(formobj)},
url: currentProjectPath+"/schemeChange/updateFileContent2.do",
dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
},
error: function(e) {},
success: function(data) {
alert("修改成功!");
}
});
}
/**
* 获取文件列表
*/
var getFileName = function() {
//取值
var fileType=$("#fileType").val();
//赋值
$.ajax({
type: 'POST',
data: {fileType:fileType},
url: currentProjectPath+"/schemeChange/queryFileName.do",
dataType: "json",
crossDomain: true,
xhrFields: {
withCredentials: true
},
error: function(e) {},
success: function(data) {
//清空
if(data.length!=0){
$("#bwName").html("");
}
//赋值
var obj=eval(data);
for(var i=0;i<obj.length;i++){
$("#bwName").append("<option value="+obj[i]+">"+obj[i]+"</option>")
}
}
});
}}
controller
@RestController
@RequestMapping("schemeChange")
public class SchemeChangeController implements BaseModelController {
//获取文件名称
static final String QUERY_FILENAME = "queryFileName";
//读取文件内容
static final String READ_FILECONTENT2 = "readFileContent2";
//更改文件内容
static final String UPDATE_FILECONTENT2 = "updateFileContent2";
/**
* 获取文件名称
* @return
*/
@RequestMapping(QUERY_FILENAME)
public ArrayList<String> getFileName(String fileType,String path){
path="E:\\报文检查系统\\schema";
ArrayList<String> files = new ArrayList<String>();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
String filename=tempList[i].getName();
if(filename.indexOf(".xsd")>=0 && filename.substring(0,1).equals(fileType)){
files.add(filename);
}
}
}
return files;
}
public static String filename="";//文件名称
String strs="";
private static LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,String>>> map0 = new LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,String>>>();
private static LinkedHashMap<String,LinkedHashMap<String,String>> map = new LinkedHashMap<String,LinkedHashMap<String,String>>();
private static LinkedHashMap<String,String> childmap = new LinkedHashMap<String,String>();
int count_current=0;
/**
* 文件内容获取
*/
@RequestMapping(READ_FILECONTENT2)
public ResponseData readFileContent2(String bwname){
System.out.println("----------------------------------------------------------------------------------------");
filename=bwname;
map0=new LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,String>>>();
try {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("E:\\报文检查系统\\schema\\"+bwname));
Element rootnode= document.getRootElement();
map0=this.nodes(rootnode);
} catch (DocumentException e) {
e.printStackTrace();
}
ResponseData responseData = ResponseDataContext.getResponseData();
responseData.writeData(map0);
responseData.setMessage("文件内容");
return responseData;
}
public LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,String>>> nodes(Element rootnode) {//得到根节点
String comments="";
for(int i = 0, size = rootnode.nodeCount(); i < size; i++){
Node node = rootnode.node(i);
if(node instanceof org.dom4j.Comment){
map = new LinkedHashMap<String,LinkedHashMap<String,String>>();//注意:不要用clear,否则会出现重复值的现象。
comments=node.getText();
}
else if (node instanceof Element) {
List<Attribute> nodelist=((Element) node).attributes();
for (Attribute attr : nodelist) {
if(!attr.getName().equals("use") && !attr.getName().equals("type") && !attr.getName().equals("maxOccurs") && !attr.getName().equals("minOccurs") ){
//当前节点
String currentnode=node.getName()+"&"+attr.getText();
//孩子节点
childmap = new LinkedHashMap<String,String>();
LinkedHashMap<String,String> childs=currentnode(node);
map.put(currentnode,childs);
map0.put(comments, map);
// System.out.println(map0);
}
}
}
}
return map0;
}
@SuppressWarnings("unchecked")
public LinkedHashMap<String,String> currentnode(Node node){
Iterator<Element> it = ((Element) node).elementIterator(); // 当前节点下面子节点迭代器
int count=0;
String param="";
String values="";
String name_min_max="";
while (it.hasNext()) {
String value="";
Element e = it.next(); //获取某个子节点对象
List<Attribute> list =e.attributes();
for (Attribute attr : list) {
value=attr.getValue();
String name=e.getName();
String name_attr=attr.getName();
if(param.equals(name)){
if(!name_attr.equals("use") && !name_attr.equals("type") && !name_attr.equals("maxOccurs") && !name_attr.equals("minOccurs") ){
values=values+","+value;
}
} else if(name.equals("minLength") || name.equals("totalDigits")){
values=value;
name_min_max=name;
} else if(name.equals("maxLength") || name.equals("fractionDigits")){
values=values+","+value;
name_min_max=name_min_max+","+name;
} else{
if(!name_attr.equals("use") && !name_attr.equals("type") && !name_attr.equals("maxOccurs") && !name_attr.equals("minOccurs") ){
param=name;
values=value;
}
}
count++;
}
if(list.size()>0){
if(count>1){
if(name_min_max.split(",").length>1){
childmap.put(name_min_max, values);
}else{
childmap.put(e.getName(), values);
}
}else{
if(!e.getName().equals("minLength") && !e.getName().equals("maxLength") && !e.getName().equals("totalDigits") && !e.getName().equals("fractionDigits")){
childmap.put(e.getName(), value);//类型、内容
}
}
}
currentnode(e);
}
return childmap;
}
/**
* 保存文件
* @param doc
*/
public void saveFile(Document doc){
try {
FileOutputStream out = new FileOutputStream("E:\\报文检查系统\\schema\\"+filename);//指定文件输出的位置
XMLWriter writer=new XMLWriter(out);//创建写出对象
writer.write(doc);//写出Document对象
doc.clone();
out.close();
writer.flush();
writer.close();//3.关闭流
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 修改文件
* @param filePath
*/
@RequestMapping(UPDATE_FILECONTENT2)
public void updateFileContent2(String formobj,String filePath){
try {
//读取文件
Document doc = new SAXReader().read(new File("E:\\报文检查系统\\schema\\"+filename));
//修改文件
Element root=doc.getRootElement();
this.rootNode(root,formobj);
//保存文件
this.saveFile(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
int count_current_child=0;
public String rootNode(Element rootnode,String newparam) {
count_current=0;
count_current_child=0;
String comments="";//注释
for(int i = 0, size = rootnode.nodeCount(); i < size; i++){
Node node = rootnode.node(i);
if(node instanceof org.dom4j.Comment){
comments=node.getText();
}
else if (node instanceof Element) {
List<Attribute> nodelist=((Element) node).attributes();
for (Attribute attr : nodelist) {
if(count_current_child>0){
count_current=count_current_child+1;
}
count_current++;
//当前节点
String newvalue=new SchemeChangeController().paramCompareUpdate(comments,node.getName(),attr.getValue(),newparam,count_current);//原则是:传递每行属性信息,方法已对属性进行处理
if(newvalue!=""){
attr.setValue(newvalue);
}
//子节点
chidNode(node,comments,newparam,count_current);
}
}
}
return strs;
}
public String chidNode(Node node,String comments,String newparam,int count_current){
String strs="";
//当前节点下面子节点迭代器
Iterator<Element> it = ((Element) node).elementIterator();
while (it.hasNext()) {
Element e = it.next(); //获取某个子节点对象
List<Attribute> list =e.attributes();
for (Attribute attr : list) {
if(!attr.getName().equals("use") && !attr.getName().equals("type") && !attr.getName().equals("maxOccurs") && !attr.getName().equals("minOccurs")){
count_current++;
String newvalue=new SchemeChangeController().paramCompareUpdate(comments,e.getName(),attr.getValue(),newparam,count_current);//原则是:传递每行属性信息,方法已对属性进行处理
if(newvalue!=""){
attr.setValue(newvalue);
}
}
}
count_current_child=count_current;
chidNode(e,comments,newparam,count_current);
}
return strs;
}
public String paramCompareUpdate(String comments,String oldtype,String oldvalue,String newstr,int count_current){
System.out.println("comments="+comments);
String newvalue="";
//解析数组字符串
JSONArray array = JSONArray.fromObject(newstr);
JSONObject fromObject = JSONObject.fromObject(array.get(count_current));
String name=fromObject.get("name").toString();
String value=fromObject.get("value").toString();
if(name.split("@").length>1){
if(name.split("@")[0].contains(",")){
if(name.split("@")[1].equals(oldvalue)){
if(name.split("@")[0].split(",")[1].equals(oldtype) || name.split("@")[0].split(",")[0].equals(oldtype)){
newvalue=value;
return newvalue;
}
}
}else{
if(name.split("@")[0].equals(oldtype) && name.split("@")[1].equals(oldvalue)){
newvalue=value;
return newvalue;
}
}
}else if(name.equals(oldtype) && !value.equals(oldvalue)){
newvalue=value;
return newvalue;
}
return newvalue;
}
}