Saving S7-300 Data to XML Files via WinCC Flexible Runtime

David Krause18 min read
SiemensTutorial / How-toWinCC
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Saving S7-300 Data to XML Files via WinCC Flexible Runtime

This technical reference documents a working field architecture that combines a legacy SIMATIC S7-300 (CPU 313) with an OP170 operator panel, a new supervisory PC running SIMATIC WinCC Flexible 2008 SP5 Runtime, and an Ewon industrial VPN router for remote publishing. The objective is to log a 16-bit temperature tag from the S7-300, persist it on disk as a structured XML file, and replicate it to a remote server at a one-hour cadence. The OP170 has no scripting engine, so the XML writer is implemented entirely in the PC-based WinCC Flexible Runtime using the built-in VBScript interpreter.

Hardware constraint: The OP170 (6AV3 617-1JC20-0AX1) ships with the Windows CE 3.0 runtime that does not expose a VBScript host. All file-IO and XML generation must therefore occur on the PC Runtime, not on the panel itself. Data must reach the PC Runtime through a tag exchange before any scripting can fire.

1. Reference Architecture

The system uses three logical layers: a control layer, a visualization layer, and a remote publishing layer. Each layer has a single responsibility, and the XML archive is written entirely in the visualization layer.

Layer Component Order Number / Firmware Function
Control S7-300 / CPU 313 6ES7 313-1AD03-0AB0, FW V2.6 Acquires PT100 via SM 331 AI, scales to INT, exposes to MPI/PROFIBUS
Visualization (local) OP170 6AV3 617-1JC20-0AX1, FW 1.5.4 Operator panel, no scripting host
Visualization (extended) WinCC Flexible 2008 SP5 Runtime on Windows 7 SP1 / Windows 10 LTSC 6AV6 621-0AA01-2AA0 (license) VBScript host, file-IO, tag polling
Connectivity CP 5611 / CP 5613 / Softnet S7 6GK1 561-1AA01 / 6GK1 713-5DB03-2Ax0 PROFIBUS DP master to the S7-300
Remote Ewon Flexy 205 / Cosy 131 EWON Flexy 205 (10/100 MBit, 4-port) VPN tunnel, Talk2M, optional FTP egress
Sink FTP/HTTP server (customer side) — Receives XML every 60 min

The CPU 313 exposes the scaled temperature tag in DB100.DBD0 (REAL) or DB100.DBW0 (INT). On the WinCC Flexible Runtime side, an internal tag named Temp_Process is mapped to that DBW through the S7-MPI/DP connection configured in the WinCC Flexible project.

2. Prerequisites

  • SIMATIC WinCC Flexible 2008 SP5 (or SP3 minimum) installed on the supervisory PC. The PC Runtime is launched through the Windows service CCAgent or the executable Siemens.exe located in C:\Program Files\Siemens\Automation\WinCC Flexible\WinCC Flexible 2008\ on x86 installations.
  • VBScript runtime enabled (it is enabled by default in the WinCC Flexible Runtime).
  • A Softnet S7 license (6GK1 704-1LW64-3AA0) or a CP 5611/CP 5613 with a HARDNET S7 license. The connection in WinCC Flexible must be of type SIMATIC S7 300/400 with the correct MPI address (default 2) or PROFIBUS address.
  • A scheduled task or in-Runtime timer (1-minute tick) for periodic appends.
  • An Ewon Flexy with a Talk2M account; the eFive protocol or the eCatcher remote access is required for outbound HTTPS/FTP.
Tag-length warning: WinCC Flexible internal tags of type 16-bit signed integer are limited to -32768..+32767. If the S7-300 transmits an INT in this range, the tag will round-trip without scaling. If the temperature is encoded as REAL in the PLC, either scale it in the PLC and transfer as INT, or change the WinCC Flexible tag to a 32-bit float (REAL/IEEE754). For negative temperatures or sub-decimal resolution, prefer the float mapping.

3. Why the OP170 Cannot Perform XML Writing

The OP170 belongs to the 170-series panels that were discontinued when Siemens moved to the Comfort and Basic Panels. Its runtime is based on Windows CE 3.0 with a stripped-down WinCC Flexible CE build. The CE Runtime:

  • Does not include a VBScript engine.
  • Does not expose FileSystemObject or ADODB.Stream.
  • Provides only the Recipe, Logging, and Alarm sub-systems for data persistence.

Attempting to script on the OP170 produces a compile error of the form "VBScript is not supported" and the function terminates at the Sub declaration. The only OP170 mechanism to export data is the Export function in the recipe view, which writes a binary .csv-flavoured file on a serial printer port or CF card. This is not XML and cannot be redirected to a TCP socket.

Therefore the XML pipeline must live on the PC Runtime. The OP170 keeps its role as a local MMI, and the PC Runtime acts as the data concentrator.

4. PC Runtime Scripting Capability

WinCC Flexible Runtime on Windows embeds a VBScript 5.6 host that supports the following automation objects:

  • HMIRuntime – reads/writes tags, schedules, events, screen navigation.
  • Screen, ScreenItems, SmartTags – object model for screen access.
  • FileSystemObject (via CreateObject("Scripting.FileSystemObject")) – text file create/append/close.
  • WScript.Shell – run external FTP client, scheduled tasks, batch files.
  • Microsoft.XMLDOM – DOM-style XML generation and validation.

Any one of these can be used to build the XML file. The most robust path is the FileSystemObject with a fixed text template, because it survives broken COM registration and survives the WinCC Flexible Runtime recovery action after a PC reboot.

5. Data Logging Alternative (Native)

Before going to scripting, consider the Data Log editor in WinCC Flexible. A data log of LoggingType = LogTag, DataFormat = CSV (tab-separated) writes a plain ASCII file with one record per cycle. The configuration lives in the project file and is signed with the WinCC Flexible compiler, so it survives Runtime restart.

Parameter Value Description
Log name TempLog Logical name in the project
Storage location D:\Logs\TempLog\ Local NTFS path; mapped network drives may drop
Trigger Cyclic, 60 s One row per minute
File extension .csv Rename suffix in post-process
Segment size 1440 rows One day per file

The native log produces a tab-separated ASCII file. To convert that to XML, run a VBScript that wraps each row in a <row> element and prepends a header. This two-step approach (data log → post-processor) decouples the timing logic from the format logic and is the recommended pattern in production sites where the tag count grows above a handful.

6. VBScript XML Writer

The following function is invoked once per minute through a WinCC Flexible scheduler (see Section 8). It opens a daily file archive_YYYYMMDD.xml, appends a <row> element, and closes the file. The file is well-formed XML and can be consumed by Excel, an HTTP server, or a custom ERP pipeline.

' WinCC Flexible VBScript - AppendRowToXml.vbs
Option Explicit

Const FOLDER = "D:\Logs\TempLog\"

Sub AppendRowToXml()
    Dim fso, ts, f, dt, year, month, day, hour, minute, second, value, row
    Set fso = CreateObject("Scripting.FileSystemObject")

    If Not fso.FolderExists(FOLDER) Then
        fso.CreateFolder(FOLDER)
    End If

    dt   = Now
    year = Right("0000" & Year(dt), 4)
    month = Right("00" & Month(dt), 2)
    day  = Right("00" & Day(dt), 2)
    hour = Right("00" & Hour(dt), 2)
    minute = Right("00" & Minute(dt), 2)
    second = Right("00" & Second(dt), 2)

    value = SmartTags("Temp_Process")
    Dim filename
    filename = FOLDER & "archive_" & year & month & day & ".xml"

    If Not fso.FileExists(filename) Then
        Set ts = fso.CreateTextFile(filename, True, False)
        ts.WriteLine "<?xml version=""1.0"" encoding=""utf-8""?>"
        ts.WriteLine "<archive source=""S7-300/CPU313"" tag=""Temp_Process"">"
    Else
        Set ts = fso.OpenTextFile(filename, 8, False, -1)
    End If

    row = "  <row t=""" & year & "-" & month & "-" & day & "T" & _
          hour & ":" & minute & ":" & second & """ v=""" & _
          CStr(value) & """/>"

    ts.WriteLine row
    ts.Close

    ' Close the archive at midnight (00:00:00)
    If hour = "00" And minute = "00" And CInt(second) < 5 Then
        Set ts = fso.OpenTextFile(filename, 8, False, -1)
        ts.WriteLine "</archive>"
        ts.Close
    End If

    Set ts = Nothing
    Set fso = Nothing
End Sub

The resulting file follows the schema used by many MES gateways and by the SIMATIC TIA Portal Openness export format described in the official TIA Portal documentation (see Structure of an XML file (TIA Portal Help)). A sample daily file looks like:

<?xml version="1.0" encoding="utf-8"?>
<archive source="S7-300/CPU313" tag="Temp_Process">
  <row t="2024-05-12T00:00:00" v="217"/>
  <row t="2024-05-12T00:01:00" v="218"/>
  <row t="2024-05-12T00:02:00" v="218"/>
  ...
  <row t="2024-05-12T23:58:00" v="221"/>
  <row t="2024-05-12T23:59:00" v="220"/>
</archive>

The closing </archive> tag is written during the first five seconds of the following day, which guarantees that the file is a well-formed XML document at all times after the very first second of day 2. If the file is consumed during the writing day, any standard XML parser will refuse it because the root element is not closed; that is the trade-off for not rewriting the file on every row. In production, simply open the next day's file before publishing.

7. DOM-Based Writer (Optional)

For installations that must publish a fully-closed XML document after every write, use the Microsoft.XMLDOM COM object. The trade-off is higher CPU cost and the requirement to keep the entire day in memory.

Sub AppendRowDom()
    Dim xmlDoc, root, row, dt, ts
    Set xmlDoc = CreateObject("Microsoft.XMLDOM")
    xmlDoc.async = False

    Dim filename
    filename = "D:\Logs\TempLog\archive_" & FormatDateTime(Now, 2) & ".xml"

    If Dir(filename) = "" Then
        Set root = xmlDoc.createElement("archive")
        root.setAttribute "source", "S7-300/CPU313"
        root.setAttribute "tag", "Temp_Process"
        xmlDoc.appendChild root
    Else
        xmlDoc.Load filename
        Set root = xmlDoc.documentElement
    End If

    Set row = xmlDoc.createElement("row")
    row.setAttribute "t", FormatDateTime(Now, vbGeneralDate)
    row.setAttribute "v", CStr(SmartTags("Temp_Process"))
    root.appendChild row

    xmlDoc.Save filename
End Sub

The DOM path also has the advantage of producing an XML file that any modern tool (Excel, Power Query, Power BI) can consume directly. The pattern is consistent with the Microsoft Excel XML export procedure where the schema mapping is auto-detected from the first row.

8. Scheduling the Script

The script is fired by a WinCC Flexible scheduler. The Runtime keeps a single-threaded event queue, so concurrent triggers will be serialized.

Property Value
Trigger type Cyclic, fixed interval
Interval 60 000 ms (1 min)
Event / function AppendRowToXml
Start time 00:00:00
End time 23:59:59

A second scheduler fires the upload script (Section 9) every 60 minutes at minute == 0. This separation of duties keeps each trigger window short and avoids blocking the tag polling thread.

9. Ewon Router: Remote Transfer to Server

The Ewon Flexy 205 provides a transparent IPsec tunnel to the customer's Talk2M account. From the Ewon's perspective, the supervisory PC is on the LAN side (10.0.0.10 in this example) and the corporate server is reached through the VPN side.

Two file-transfer methods are field-proven with WinCC Flexible Runtime on a PC.

9.1 FTP via Windows command line

Use WScript.Shell to run a batch file that pushes the daily file through the Ewon tunnel.

Sub UploadHourly()
    Dim wsh, cmd, dt, fname
    Set wsh = CreateObject("WScript.Shell")
    dt = Year(Now) & Right("00" & Month(Now), 2) & Right("00" & Day(Now), 2)
    fname = "D:\Logs\TempLog\archive_" & dt & ".xml"
    cmd  = "cmd /c echo open ftp.corp.example.com > D:\Logs\TempLog\ftp.scr && " & _
           "echo user cust123 secret >> D:\Logs\TempLog\ftp.scr && " & _
           "echo binary >> D:\Logs\TempLog\ftp.scr && " & _
           "echo put " & fname & " >> D:\Logs\TempLog\ftp.scr && " & _
           "echo bye >> D:\Logs\TempLog\ftp.scr && " & _
           "ftp -s:D:\Logs\TempLog\ftp.scr"
    wsh.Run cmd, 0, True
    Set wsh = Nothing
End Sub
Security note: Embedding a plain-text password in a .scr file is acceptable for non-critical telemetry but should be replaced by a key-only SSH key exchange on customer sites with IT security audits. The Ewon Flexy also supports a built-in SFTP client that can be triggered by an HTTP request.

9.2 HTTP POST via the Ewon Web Server

The Ewon Flexy exposes an HTTP endpoint at http://10.0.0.1/mimic/cgi-bin/awblock.egi and supports custom tags. An alternative is the ewon-http server-side script tag that posts to a corporate URL. The PC Runtime does an HTTP POST through MSXML2.XMLHTTP:

Sub UploadHttp()
    Dim http, payload, dt, fname, ts, body
    Set http = CreateObject("MSXML2.XMLHTTP.6.0")
    dt = Year(Now) & Right("00" & Month(Now), 2) & Right("00" & Day(Now), 2)
    fname = "D:\Logs\TempLog\archive_" & dt & ".xml"

    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts  = fso.OpenTextFile(fname, 1, False, -1)
    body = ts.ReadAll
    ts.Close

    http.open "POST", "https://api.corp.example.com/ingest", False
    http.setRequestHeader "Content-Type", "application/xml"
    http.setRequestHeader "X-Site", "plant1-s7300"
    http.send body
    Set http = Nothing
End Sub

The HTTPS endpoint is reached through the Ewon VPN, which provides mutual authentication on the IPsec layer; the application layer can therefore run plain HTTPS without exposing the corporate CA to the plant network.

10. CP 343-1 ERPC: Direct PLC-to-ERP Path

If the requirement is to bypass the HMI and have the S7-300 send the temperature directly to an MES/ERP database, the alternative is a CP 343-1 ERPC (Ethernet/TCP/IP, with embedded RPC client). The CPU 313 alone cannot open TCP sockets, so a CP is required. The CP 343-1 ERPC order number is 6GK7 343-1EX30-0XE0 (or 6GK7 343-1EX21-0XE0 on legacy hardware).

Configuration steps:

  1. Insert the CP 343-1 ERPC into the S7-300 rail and assign an IP address in STEP 7 HW Config (for example 192.168.10.20).
  2. Set the CP to ERPC mode (not standard TCP). In NetPro, open the CP properties and choose ERPC as the active connection. Add the connection partner (the MES/ERP server) by IP and port.
  3. Call the standard FB FB 245 (or the vendor-supplied CP 343-1 ERPC function block) from the S7-300 user program. The block accepts a connection ID, a DB with payload length and pointer, and returns status codes in RET_VAL and STATUS.
  4. Pack the temperature INT into a structured DB, build an XML envelope in the DB, and pass it to the FB. The CP transmits it to the ERP host.
  5. On the MES/ERP side, install a small daemon that listens on the configured TCP port and inserts the rows into the database.

This path removes the PC Runtime from the critical path and is the correct choice when the PC's reliability cannot be guaranteed (e.g., 24/7 operation). The HMI continues to display the temperature, but the archive lives in the MES/ERP system.

11. Tag Mapping Reference

The mapping between the S7-300 DB and the WinCC Flexible tag must be configured in the project under Communication > Tags. The CP 5611/CP 5613 PROFIBUS connection is named PROFIBUS_DP in this example.

WinCC Flexible Tag PLC Address Data Type Length Acquisition
Temp_Process DB100.DBW0 INT 2 Cyclic 1 s
Temp_Raw DB100.DBW2 INT 2 On demand
Tag_Quality DB100.DBX4.0 BOOL 0.1 Cyclic 5 s
Last_Archive DB100.DBB10 STRING[8] 8 On change

Make sure the Connection property of each tag references PROFIBUS_DP and the Address property uses the dot notation DB100.DBW0. Acquisitions in the millisecond range are not supported by PROFIBUS DP at typical baud rates; 1 s is the safe floor.

12. Verification Steps

  1. Initial smoke test. In the WinCC Flexible Runtime, open the Diagnostic screen and confirm that Temp_Process is updating once per second. The animation should be live.
  2. File generation. Wait for the 1-minute scheduler to fire. Open D:\Logs\TempLog\ in Explorer and confirm that archive_YYYYMMDD.xml exists, is not empty, and has more than one <row> element.
  3. XML well-formedness. Open the file in Internet Explorer or Notepad++. Run the XML Tools > Validate Now plugin against W3C XML 1.0. There must be no error.
  4. Schema binding. Open the file in Microsoft Excel using File > Open > XML. Excel must auto-detect the two columns t and v and load them into cells. This is the same procedure described in the Export XML data in Excel support article.
  5. Upload verification. Wait for the 60-minute scheduler to fire. Check the corporate FTP site or the API ingest log for a new file with a 200 status code. If a 401/403 appears, the Ewon tunnel authentication is the likely cause.
  6. Ewon tunnel. Log in to eCatcher, open the Talk2M account, and confirm that the Flexy has been online for the duration of the upload window. The Flexy must have a stable WAN light and a VPN light on its front panel.
  7. End-of-day close. At 00:00:00 of the next day, open the previous day's file. It must contain a closing </archive> tag on the last line.

13. Commissioning Checklist

  • PLC: DB100 created with DBW0 (INT temperature), DBX4.0 (quality), DBB10 (last-archive timestamp STRING[8]).
  • WinCC Flexible: connection PROFIBUS_DP configured and tested, four tags mapped.
  • Runtime: VBScript project compiled with the two subroutines AppendRowToXml and UploadHttp.
  • Schedulers: 60 s cyclic for append, 3600 s cyclic for upload.
  • Folder: D:\Logs\TempLog\ created with Users having write permission (the Runtime service may run as SYSTEM).
  • Ewon: Talk2M account, VPN key installed, Flexy reachable at 10.0.0.1 from the PC.
  • Network: outbound TCP/443 and TCP/21 from the Flexy to the corporate endpoint permitted by the customer's firewall.
  • Backup: a weekly zip of D:\Logs\TempLog\ on an external USB drive.

14. Troubleshooting Matrix

Symptom Root Cause Remedy
File archive_*.xml not created Folder path does not exist or Runtime service has no write permission Pre-create D:\Logs\TempLog\ and grant write to SYSTEM and Users
Appends stop after a few rows VBScript runtime error in SmartTags call Open the WinCC Flexible AlarmLog; look for entries of class Script error; rename tag if misspelled
XML file unparseable on the server side Last </archive> not yet written (file still open during the day) Either consume the file after 00:00:05, or switch to the DOM writer (Section 7) that closes the file after every write
Tag value always 0 PLC connection configured but not in Runtime state Verify the PROFIBUS cable, the CP 5611 driver in SIMATIC Manager > Set PG/PC Interface, and the CPU MPI/DP address (default 2)
Ewon tunnel times out Flexy is in OFFLINE mode or Talk2M key has expired Re-export the VPN key from eCatcher, re-import it on the Flexy through ebuddy, and power-cycle
HTTP 401/403 from corporate API API key not in header, or Egress IP is whitelisted incorrectly Ask the API owner to whitelist the Flexy's Talk2M egress IP range; confirm the API key in the VBScript header
File created but data column is empty Tag of wrong length (DBW0 mapped but DB has a BOOL at offset 0) Check the DB layout in STEP 7; ensure DBW0 starts on a word boundary
Schematic: one row per minute but only one row per day Scheduler is set to Once per day instead of Cyclic Reconfigure scheduler trigger to Cyclic with 60 s interval
OP170 shows 'Connection interrupted' but PC shows live tags OP170 on a separate PROFIBUS node, address conflict Change OP170's PROFIBUS address to a free one (e.g., 4) and rerun Transfer from the project

15. Field-Proven Caveats

  • Disk I/O on slow CF cards. Older PCs in plant cabinets still ship with industrial CF cards rated at 4 MB/s sequential write. Opening and closing a small file 1440 times a day is not a bottleneck, but writing the entire 24-hour file in one DOM Save call can saturate the bus. Prefer the appending model on CF-backed systems.
  • Unicode codepage. The OP170 and the S7-300 exchange strings in Latin-1 by default. If the tag value carries units (e.g., °C), make sure the WinCC Flexible Runtime is set to UTF-8 in the project options. Otherwise Excel will display the degree sign as a question mark.
  • Daylight saving time. The 60-minute upload window at minute 0 will fire twice in autumn and skip once in spring. Add a one-minute tolerance in the server-side ingest to avoid duplicate processing.
  • Power loss recovery. WinCC Flexible Runtime buffers unsaved scheduler triggers for up to 30 s. If the PC loses power at minute 0, the next boot will fire the missed trigger within 30 s. The XML file is auto-reopened by the VBScript on first call, so no manual recovery is required.
  • Anti-virus quarantine. Some endpoint protection suites quarantine the Siemens.exe child process that hosts the VBScript. Add the D:\Logs\TempLog\ directory to the AV exclusion list and exclude the WinCC Flexible installation path from real-time scanning.

16. Architecture Diagram

The following inline SVG captures the full data path from the PT100 sensor to the corporate server. The OP170 and the PC Runtime share the same PROFIBUS network and read the same DB; only the PC Runtime runs the VBScript.

PT100 Sensor SM 331 AI 6ES7 331-7KF02 S7-300 CPU 313 DB100.DBW0 = INT OP170 Panel 6AV3 617-1JC20 CP 343-1 ERPC MES/ERP path PC Runtime WinCC Flexible 2008 SP5 VBScript host 60 s scheduler + 60 min upload D:\Logs\TempLog\*.xml Ewon Flexy 205 Talk2M VPN tunnel Outbound HTTPS/FTP 10.0.0.1 LAN side

17. Frequently Asked Questions

Can the OP170 itself write the XML file?

No. The OP170 (firmware 1.5.4 on Windows CE 3.0) does not include a VBScript engine and exposes no file-IO COM objects. The XML must be written on the PC Runtime that hosts WinCC Flexible 2008 SP5 or later; the OP170 only displays the values.

What is the recommended interval for the VBScript trigger?

60 s for the appender and 3600 s for the uploader. Going below 60 s on PROFIBUS DP at 1.5 Mbit/s will starve the tag polling, and the WinCC Flexible scheduler minimum resolution is 100 ms; for a 1-minute sample, 60 000 ms is the canonical choice.

Does the CPU 313 itself need a CP 343-1 to send the data over Ethernet?

Yes. The CPU 313 has no integrated PROFINET or Ethernet interface. To send TCP traffic from the PLC, install a CP 343-1 (6GK7 343-1EX30-0XE0) or a CP 343-1 ERPC, configure an IP address in HW Config, and call the supplied FB (FB 245 for the ERPC variant) from OB1.

How do I protect the FTP password used in the upload script?

Replace the plain-text user cust123 secret line with an SFTP key exchange. Generate a 2048-bit RSA key with PuTTYgen, install the public key on the corporate SFTP server, and use the pageant agent to hold the private key on the supervisory PC. Avoid the echo user pattern on sites with security audits.

What happens if the PC loses power in the middle of a write?

The WinCC Flexible Runtime buffers scheduler triggers for up to 30 s, so a short power dip causes a delay but no data loss. A full power loss leaves the daily XML file with a partial row; the next AppendRowToXml call opens the same file in append mode and continues. The script is idempotent at the row level: any half-written line at the end of the file can be trimmed by the server-side parser.

Can Excel open the XML file directly?

Yes. Use File > Open > XML in Excel. The two attributes t and v are auto-detected as columns. The procedure is the same as the one described in the Microsoft Excel XML data support article, and the resulting schema can be saved as .xsd for ingestion into Power BI, Tableau, or any XML-aware MES.

Back to blog