读取和更新salesforce的static resource中的XML文件

很久没来园子,一是工作忙,而是生活的一些琐事让我不能“闲下来”;最近刚忙完了一些项目,时间上有些空闲,来园子里逛了一下,突然有写博客的冲动。

从刚工作到现在,自己也工作四年了,一直做的都是基于salesforce平台的开发和系统集成的工作。这些年对这个平台也有一些“积累”,以后可能会写一些关于这个平台的一些博客,或技术,或吐槽。

 

闲话不提,最近做了一个项目,是要读取和更新存在salesforce的static resource的一个xml文件。这个xml文件维护着一个公司的产品和服务的信息,之前每次都得download下来,手动编辑。由于文件比较大,可能不太好管理和编辑,就有一个需求用VF Page来读取这个XML文件,并根据节点数据格式显示在页面中,编辑后,可以更新这个xml文件。

之前一直以为static resource中的东西不能用代码来更改,后来查了一些文档,并用一些工具截取了一些http的请求,发现我们可以构建一个httprequest,往salesforce post过去就可以更新这个xml文件了。


整体结构为:2个实体类XmlNode和XmlDocument用来存xml的一些信息, 一个Helper类,用于解析/读存XML文件, 还有一个页面后台的controller以及一个VF page来显示和编辑xml文件。


项目的关键点和难点在于如何更新这个xml文件,通过研究往salesforce post下面的xml string就可以更新制定的xml 文件:

// Uploades the updated xml file to static resource
    private static Boolean updateXml(String newXMLStr, String serverUrl)
    {  
            Boolean result = false;
        newXMLStr = EncodingUtil.base64Encode(Blob.valueOf(newXMLStr));
        // the meta data used to post to salesforce to update static resource
        String metaData = '<?xml version="1.0" encoding="utf-8" ?>'+
                            '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
                                '<soap:Header>'+
                                    '<SessionHeader xmlns="http://soap.sforce.com/2006/04/metadata">'+
                                        '<sessionId>' + UserInfo.getSessionId() + '</sessionId>'+ 
                                    '</SessionHeader>'+
                                '</soap:Header>'+
                                '<soap:Body>'+
                                    '<update xmlns="http://soap.sforce.com/2006/04/metadata">'+
                                        '<UpdateMetadata>'+
                                            '<currentName>' + resourceName + '</currentName>'+
                                            '<metadata xsi:type="StaticResource">'+
                                                '<fullName>' + resourceName + '</fullName>'+
                                                '<content>' + newXMLStr + '</content>'+
                                                '<cacheControl>Public</cacheControl>'+
                                                '<contentType>text/xml</contentType>'+
                                            '</metadata>'+
                                        '</UpdateMetadata>'+
                                    '</update>'+
                                '</soap:Body>'+
                            '</soap:Envelope>';
        HttpResponse response = requestForResponse(metaData, serverUrl);        
        // if success, return the response body
        if(response.getStatusCode() == 200)
        {
            result = true;
        }
        return result;
    }
posted @ 2012-11-08 16:28  david.lee  阅读(493)  评论(0编辑  收藏  举报