xml文件数据上报——根据模型生成对应的xml文件进行上报

Posted lovable

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xml文件数据上报——根据模型生成对应的xml文件进行上报相关的知识,希望对你有一定的参考价值。

1.引入命名空间:System.Xml

2.xml数据格式-xml存放位置 XmlFilesjgsjAddAdminSuperItemInfo.xml

技术分享图片
<?xml version="1.0" encoding="utf-8" ?>
<!--新增行政监管事项信息-->
<Data>
  <AdminSuperItemInfo>
    <tenderProjectName>项目名称</tenderProjectName>
    <tenderProjectCode>项目编号</tenderProjectCode>
    <bidSectionCode>标段(包)编号</bidSectionCode>
    <bidSectionName>标段(包)名称</bidSectionName>
    <unifiedDealCode>统一交易标识码</unifiedDealCode>
    <projectType>项目类型</projectType>
    <tradeType>交易方式</tradeType>
    <tradeStep>交易环节</tradeStep>
    <approvalProject>监管事项</approvalProject>
    <goverment>监管单位</goverment>
    <area>行政区域</area>
    <law>法律法规政策依据</law>
    <isPast>是否通过</isPast>
    <content>监管意见</content>
    <signature>审批人电子签名</signature>
    <attachmentSetCode>【附件】附件关联标识号</attachmentSetCode>
    <approvalDate>监管时间</approvalDate>
    <platformCode>交易平台标识码</platformCode>
    <pubServicePlatCode>公共服务平台标识码</pubServicePlatCode>
    <dataTimestamp>数据时间戳</dataTimestamp>
  </AdminSuperItemInfo>
</Data>
View Code
技术分享图片
<?xml version="1.0" encoding="utf-8" ?>
<Data>
  <File>
    <fileByte>BASE64加密(Byte[]数据)</fileByte>
    <fileName>文件名称</fileName>
    <fileTitle>文件标题(如:立项批复文件(项目审批核准文件))</fileTitle>
  </File>
</Data>
UploadFile.xml

3.上报

protected void btnReport_Click(object sender, EventArgs e)
{
//上报
XmlDataDocument doc = new XmlDataDocument();
//加载xml文件
             doc.Load(Server.MapPath(@"XmlFilesjgsjAddAdminSuperItemInfo.xml"));
string log = "";
//保存新加载的xml文件 用于测试上报的时候使用
log = doc.InnerXml;
//获取节点的所有子节点
var nodes = doc.SelectSingleNode("/Data/AdminSuperItemInfo").ChildNodes;
//XTYPE 是通过反射的方法获取S_ZADMINSUPERITEMINFO表中的特定数据 这里可以重新查询出相应的数据进行填充
S_ZADMINSUPERITEMINFO project = XTYPE as S_ZADMINSUPERITEMINFO;
技术分享图片
#region xml数据组装
            //fileds为需要显示的数据
            foreach (var filed in fileds)
            {
                string fileUploadNames = "";
                //取到属性
                PropertyInfo property = type.GetProperty(filed.FiledName.ToUpper());
                //找到project类中property属性的值
                var value = property.GetValue(project);
                //当前filed.FiledName是否是文件上传控件 如果是就需要向省上上报附件文件
                var fileControl = SpecialControls.FirstOrDefault(p => p.CType == ContorlType.fileUpload && p.FiledName.ToLower() == filed.FiledName.ToLower());
                //是附件 并且有值的时候进行上报
                #region 上报附件
                if (fileControl != null && value != null)
                {
                    //处理上传文件 各文件之间用分号隔开
                    string[] fileNames = value.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    XmlDataDocument fileDoc = new XmlDataDocument();
                    //获取上报附件的xml文件
                    fileDoc.Load(Server.MapPath(@"XmlFilesUploadFile.xml"));
                    //创建此节点的一个副本
                    var fileNode = fileDoc.SelectSingleNode("/Data/File").Clone();
                    //移出所有子节点
                    fileDoc.SelectSingleNode("/Data").RemoveAll();
                    foreach (var fileName in fileNames)
                    {
                        XmlNode newFileNode = fileNode.Clone();
                        //循环加载附件
                        //读取文件转换为Base64
                        string base64Str = Common.FileConvertBase64(Server.MapPath(fileName));
                        string fileSortName = fileName.Substring(fileName.LastIndexOf("/") + 1, fileName.Length - fileName.LastIndexOf("/") - 1);
                        fileSortName = fileSortName.Substring(0, fileSortName.LastIndexOf("_")) + fileSortName.Substring(fileSortName.LastIndexOf("."), fileSortName.Length - fileSortName.LastIndexOf("."));
                        //替换xml文件中的值
                        newFileNode.SelectSingleNode("/fileByte").InnerText = base64Str;
                        newFileNode.SelectSingleNode("/fileName").InnerText = fileSortName;
                        newFileNode.SelectSingleNode("/fileTitle").InnerText = fileSortName.Substring(0, fileSortName.LastIndexOf("."));
                        fileDoc.SelectSingleNode("/Data").AppendChild(newFileNode);
                    }
                    //使用省上的接口进行上报数据
                    using (ScToubao.toubiaoSoapClient toubiao = new ScToubao.toubiaoSoapClient())
                    {
                        //上传文件的附件
                        string uploadResult = toubiao.UpLoadFile(APIKEY, fileDoc.InnerXml);
                        XmlDocument uploadDoc = new XmlDocument();
                        uploadDoc.LoadXml(uploadResult);
                        if (uploadDoc.SelectSingleNode("/Result/Status").InnerText.Trim() == "1")
                        {
                            fileUploadNames = uploadDoc.SelectSingleNode("/Result/Details").InnerText.Trim();
                        }
                        using (LsyjEntities data = new LsyjEntities())
                        {
                            //记录上报日志
                            DataLog.AddReportLog(data, int.Parse(uploadDoc.SelectSingleNode("/Result/Status").InnerText.Trim()), (int)userInfo.ID, 0, "XX", "UpLoadFile", uploadResult);
                            data.SaveChanges();
                        }
                        if (fileUploadNames.Length > 0)
                            fileUploadNames = fileUploadNames.Replace(",", ";");
                    }
                }
                #endregion
                #region 组装其他需要上报的数据
                foreach (XmlElement node in nodes)
                {
                    //类属性名称和xml节点名称一致
                    if (node.Name.ToUpper() == filed.FiledName)
                    {

                        node.InnerText = "";
                        if (fileUploadNames.Length > 0)
                            node.InnerText = fileUploadNames;
                        else
                            if (value != null)
                            {
                                if (value.GetType().Name == "DateTime")
                                    node.InnerText = ((DateTime)value).ToString("yyyyMMddHHmmss");
                                else
                                    node.InnerText = value.ToString();
                            }
                            else
                                node.InnerText = "";
                    }
                }
                #endregion
            }
            #endregion
xml数据组装及附件上报
string result = "";
技术分享图片
#region 测试服务器上报数据 TestReg 先测试上报,如果测试上报不成功,则不能上报
            string msg;
            if (!TestReport.Report(doc.InnerXml, ReportDataType.AddAdminSuperItemInfo, out msg))
            {
                XmlDocument root = new XmlDocument();
                root.LoadXml(log);
                var nodess = root.SelectSingleNode("/Data/AdminSuperItemInfo").ChildNodes;
                foreach (XmlElement node in nodess)
                {
                    if (msg.Contains(node.Name))
                    {
                        var na = node.Name;
                        var news = node.InnerText;
                        msg = msg.Replace(na + "", news);
                    }
                }
                project.REMARK = ConfigurationManager.AppSettings["Msg"] + msg;
                project.ISSENDOK = -2;
                using (LsyjEntities data = new LsyjEntities())
                {
                    data.Entry(project).State = System.Data.EntityState.Modified;
                    data.SaveChanges();
                }
                Response.Write(string.Format("<script type=‘text/javascript‘>alert(‘{0}‘);</script>", msg));
                return;
            }
            #endregion
测试服务器上报数据 TestReg 先测试上报,如果测试上报不成功,则不能上报
技术分享图片
#region 正式上报数据
            try
            {
                using (ScToubao.toubiaoSoapClient toubiao = new ScToubao.toubiaoSoapClient())
                {
                    result = toubiao.AddAdminSuperItemInfo(APIKEY, doc.InnerXml);
                    XmlDocument docResult = new XmlDocument();
                    docResult.LoadXml(result);
                    int isOk = int.Parse(docResult.SelectSingleNode("/Result/Status").InnerText);
                    //0:编辑;1,提交审核;-1,审核退回;2,报送成功;-2,报送异常
                    if (isOk == 1)
                        project.ISSENDOK = 2;
                    else
                        project.ISSENDOK = -2;

                    using (LsyjEntities data = new LsyjEntities())
                    {
                        //记录日志
                        DataLog.AddOperationLog(data, Request.UserHostAddress, (int)userInfo.ID, project.ADMINSUPERITEMINFOID + ",上报", OperationType.Report, project.ADMINSUPERITEMINFOID, "S_ZADMINSUPERITEMINFO");
                        //记录上报日志
                        DataLog.AddReportLog(data, isOk, (int)userInfo.ID, (int)project.ADMINSUPERITEMINFOID, "S_ZADMINSUPERITEMINFO", "AdminSuperItemInfo", result);
                        //如果上报异常,记录异常原因
                        string content = "";
                        if (project.ISSENDOK == -2)
                        {
                            content = docResult.SelectSingleNode("/Result/Details").InnerText;
                            XmlDocument root = new XmlDocument();
                            root.LoadXml(log);
                            var nodess = root.SelectSingleNode("/Data/AdminSuperItemInfo").ChildNodes;
                            foreach (XmlElement node in nodess)
                            {
                                if (content.Contains(node.Name))
                                {
                                    var na = node.Name;
                                    var news = node.InnerText;
                                    content = content.Replace(na + "", news);
                                }
                            }
                            project.REMARK = content;
                            var url = HttpContext.Current.Request.Url.AbsolutePath.ToString().Replace("Edit", "List").Replace("edit", "List");
                            Response.Write(string.Format("<script type=‘text/javascript‘>alert(‘{0}‘); window.location.href =‘" + url + "‘;</script>", content));
                        }
                        if (project.ISSENDOK == 2)
                        {
                            project.REMARK = "";
                        }
                        data.Entry(project).State = System.Data.EntityState.Modified;
                        data.SaveChanges();
                        //if (project.ISSENDOK != -2)
                        //{
                        //    Response.Write(string.Format("<script type=‘text/javascript‘>alert(‘{0}‘) ;window.location.href =‘{1}‘;</script>", "报送成功", HttpContext.Current.Request.Url.AbsolutePath.ToString().Replace("Edit", "List")));
                        //}
                        if (content != "")
                        {
                            Response.Write(string.Format("<script type=‘text/javascript‘>alert(‘{0}‘);window.location.href =‘{1}‘;</script>", content, HttpContext.Current.Request.Url.ToString()));
                            return;
                        }
                        else
                        {
                            Response.Write(string.Format("<script type=‘text/javascript‘>alert(‘{0}‘) ;window.location.href =‘{1}‘;</script>", "报送成功", HttpContext.Current.Request.Url.AbsolutePath.ToString().Replace("Edit", "List")));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Lsyj.Common.Common.WriteExceptionLog(ex);
            }
            #endregion
正式上报数据
}

其他、通过反射调用接口方法

string msg="";
Report("需要上报的doc.InnerXml文件", "AddAdminSuperItemInfo", out msg);
/// <summary>
        /// 数据上报
        /// </summary>
        /// <param name="xmlString">需要上报的xml文件</param>
        /// <param name="dataType">需要上报的方法名称 可以定义为枚举 以防写作</param>
        /// <param name="msg">输出的msg文件</param>
        /// <returns></returns>
        public static bool Report(string xmlString, ReportDataType dataType, out string msg)
        {
            //配置文件判断是否需要上报 1需要上报
            if (ConfigurationManager.AppSettings["istest"] + "" == "1")
            {
                msg = "";
                //省上上报apikey
                string testApiKey = ConfigurationManager.AppSettings["TESTAPIKEY"];
                string result = "";
                //toubiaoSoapClient 通过服务引用得到的类
                Type type = typeof(TestScToubiao.toubiaoSoapClient);
                //获取该类下的指定的公共方法
                MethodInfo method = type.GetMethod(dataType.ToString());
                using (TestScToubiao.toubiaoSoapClient toubiao = new TestScToubiao.toubiaoSoapClient())
                {
//调用相应的上报方法 result
= (string)method.Invoke(toubiao, new object[] { testApiKey, xmlString }); } XmlDocument docResult = new XmlDocument(); docResult.LoadXml(result); int isOk = int.Parse(docResult.SelectSingleNode("/Result/Status").InnerText); if (isOk == 1) return true; else { msg = docResult.SelectSingleNode("/Result/Details").InnerText; string emailflag = ",";
            //判断返回的数据是否包含某些字符或字符串
if ((Regex.Matches(msg, emailflag).Count == 1 || Regex.Matches(msg, "").Count == 1) && msg.IndexOf("数据库中未查询到相关信息") > 0) { msg = ""; return true; } else return false; } } else { msg = ""; return true; } }

fileds、XTYPE详情见于:https://www.cnblogs.com/lovable/p/9186459.html这篇文章




以上是关于xml文件数据上报——根据模型生成对应的xml文件进行上报的主要内容,如果未能解决你的问题,请参考以下文章

xml文件生成与下载

Hibernate的SQL语句是怎么根据XML配置文件生成的(实现原理)

在Java的xml文件如何将一个系统数据对应到另一个系统对应表的对应字段,这个过程如何在xml文件中体现出来

接口测试-soapui-根据excle数据自动生成xml请求

Mybatis 映射文件

如何根据xml和schema文件生成java类(用程序实现)!