Salesforce consuming XML and display data in Visua

2019-05-30 02:04发布

问题:

Firstly, this question requires a bit of introduction so please bear with me.

The high level is that I am connecting to a outside web service which will return some XML to my apex controller. The idea is that I want to display the XML returned into a nice tabular format in a VisualForce page. The format of the XML coming back will look something like this:

<Wrapper><reportTable name='table_id' title='Report Title'>
  <row>
    <Element1><![CDATA[campaign_id]]></Element1>
    <Element2><![CDATA[577373]]></Element2>
    <Element3><![CDATA[4129]]></Element3>
    <Element4 dataFormat='2' dataSuffix='%'><![CDATA[0.7151]]></Element4>
    <Element5><![CDATA[2010-04-04]]></Element5>
    <Element6><![CDATA[2010-05-03]]></Element6>
  </row>
</reportTable>

...

Now currently I am using the XMLdom utility class (developed by SF for XML functions) to map this data into a custom object "reportTable" which contains a list of "row" custom objects. The reason I am building it out this way is because I don't know how many elements will be in each row, nor the number of rows.

The Visualforce page looks something like this:

<table><apex:repeat value="{!reportTables}" var="table">
  <apex:repeat value="{!table.rows}" var="row">
  <tr>
   <apex:repeat value="{!row.ColumnValue}" var="column">
    <apex:repeat value="{!column}" var="value">
     <td>
     <apex:outputText value="{!value}" />
     </td>
    </apex:repeat>
   </apex:repeat>
   </tr>
  </apex:repeat>

Questions are:

1) Does this seem like a good approach to the problem?

2) Is there a simpler/better way to consume the XML besides writing my own custom objects to map VF to?

Open to any and all suggestions. I really hope there is a better way than building the HTML table myself, as then I also have to deal with styling and alignment etc. Thanks.

回答1:

Since you're returning the XML directly to your controller, define and use a wrapper class, with properties (even additional collections for undefined row lengths) for each XML node needed. It's often what needs to be done to display tabular data from across multiple objects. A collection of your wrapper objects will allow you to iterate over them, and use dot notation to access the fields in the class.