Editing TIA V15.1 LAD via XML Export and Import
Most machine programs are written in LAD, which is graphical rather than text. To let tools read and edit them, I have to work with the XML behind those diagrams, and first prove that nothing is lost on the round trip.
1-minute summary
- Symptom / problem
- LAD in TIA V15.1 cannot be generated as text, so an AI cannot read or edit it directly
- Who should read
- People who want tools or an AI to read and edit LAD programs in TIA Portal V15.1
- Fix in short
- Export to SimaticML, turn the XML into per-network text, edit or add networks with a script, then import back with Override. Nine traps are listed.
I needed to add networks to several LAD blocks in a TIA Portal V15.1 project, and I wanted AI to read the entire existing program before making changes. I ran Generate source from blocks to get the program out as text. It skipped every LAD block and produced only SCL and DB files. My sample project had 84 LAD blocks out of 140, so almost all the substance of the program was invisible. I had to take an indirect route: export XML, convert it to text myself, edit the XML, then import it back. This article follows the steps I actually took, along with the pitfalls I encountered.
Importing with Override overwrites the existing block without asking. I performed every step in this article on a copy of the project and checked the results only on a simulator. I never downloaded it to a real PLC. Before a program edited this way reaches a machine, it must be reviewed and approved by the engineer responsible for that machine.
V15.1 can generate text for only four types, and LAD is not one of them
In V15.1, Generate source from blocks works only with SCL, STL, DB and UDT. LAD, FBD and GRAPH cannot be output as text. The only way to get LAD content into a file is to export the block as XML in a format called SimaticML, which is available through TIA Openness. I covered connecting PowerShell to TIA in the article on connecting AI through Openness. Here, I assume I already have a $sw variable holding PlcSoftware.
SCL, STL, DB, UDT
Produces text files that can be read immediately and imported back as external sources, but covers only a small part of a machine program. In the sample project, that means 15 SCL blocks.
LAD, FBD and other blocks
Produces XML that stores each network as a list of parts and the wires connecting them. It is too much to read directly and needs a converter, but it is the only way to access the 84 LAD blocks.
First prove that the round trip does not break anything
Before editing anything, I needed to know for certain that exporting and importing back produced the same block, rather than one that looked the same but failed to compile. I verified this step by step, starting with no edits at all.
- Copy the entire project folder, then use
Projects.Opento open the copy. - Export one FC as XML and import it back without changing a single character, then compile. The result must be 0 errors.
- Rename two spare tags to the new names I plan to use.
- Append networks 9 and 10 to the FC, each containing one contact connected to one coil. Import and compile. The result must be 0 errors.
- Export it again for inspection, then open it in the LAD editor and visually check that the new networks look correct.
Step 2 is the one people often skip, but it is the control for the entire experiment. If importing an unchanged block fails to compile, the problem is in the procedure, not in the edits. That saves me from chasing faults in XML I wrote myself.
# หา block กับ group ที่มันอยู่ (import ต้องลง group เดิม)
function FindBlock($g, $n) {
foreach ($b in $g.Blocks) { if ($b.Name -eq $n) { return @($g, $b) } }
foreach ($s in $g.Groups) { $r = FindBlock $s $n; if ($r) { return $r } }
}
$g, $block = FindBlock $sw.BlockGroup 'FC_Station'
# export: ไฟล์ปลายทางต้องยังไม่มีอยู่ ไม่งั้น Export โยน exception
$f = 'C:\Work\xml\FC_Station.xml'
Remove-Item $f -ErrorAction SilentlyContinue
$block.Export([IO.FileInfo]$f, [Siemens.Engineering.ExportOptions]::WithDefaults)
# import กลับลง group เดิม แบบเขียนทับ
$g.Blocks.Import([IO.FileInfo]$f, [Siemens.Engineering.ImportOptions]::Override) | Out-Null
# compile แล้วอ่านผลทุกครั้ง
$cc = $sw.GetType().GetMethod('GetService').MakeGenericMethod(
[Siemens.Engineering.Compiler.ICompilable]).Invoke($sw, $null)
$res = $cc.Compile()
"COMPILE state=$($res.State) errors=$($res.ErrorCount) warnings=$($res.WarningCount)"
The SimaticML structure of one network
In the XML file, each network is an element named SW.Blocks.CompileUnit. Inside it is NetworkSource, containing FlgNet, which in V15.1 uses a namespace ending in NetworkSource/FlgNet/v3. FlgNet has two sections: Parts and Wires.
Parts stores two kinds of objects. The first is Access, which represents a referenced variable. It contains a Symbol, with the name split into a Component at each level. The second is Part, which represents an element on the rung, such as Contact, Coil or an O box that joins parallel branches. An NC contact is a Part with a child named Negated, indicating that the operand pin is inverted. Each object has its own UId number.
Wires contains the connections between UIds. There are three forms to know: Powerrail is the left power rail, IdentCon connects a variable to an element's operand pin, and NameCon is a named pin, such as in or out. A network with one contact connected to one coil looks like this.
<FlgNet xmlns="http://www.siemens.com/automation/Openness/SW/NetworkSource/FlgNet/v3">
<Parts>
<Access Scope="GlobalVariable" UId="21">
<Symbol>
<Component Name="DB_Act" />
<Component Name="Clamp" />
<Component Name="Lower" />
<Component Name="Out" />
</Symbol>
</Access>
<Access Scope="GlobalVariable" UId="22">
<Symbol>
<Component Name="Valve_Down" />
</Symbol>
</Access>
<Part Name="Contact" UId="23" />
<Part Name="Coil" UId="24" />
</Parts>
<Wires>
<Wire UId="25"><IdentCon UId="21" /><NameCon UId="23" Name="operand" /></Wire>
<Wire UId="26"><IdentCon UId="22" /><NameCon UId="24" Name="operand" /></Wire>
<Wire UId="27"><Powerrail /><NameCon UId="23" Name="in" /></Wire>
<Wire UId="28"><NameCon UId="23" Name="out" /><NameCon UId="24" Name="in" /></Wire>
</Wires>
</FlgNet>
Following the wires shows that the power rail connects to the in pin of contact 23, whose operand is DB_Act.Clamp.Lower.Out. The contact's out pin then connects to the in pin of coil 24, whose operand is Valve_Down. These twenty-odd lines represent a single rung that shows only a contact and a coil in the diagram. AI can read XML like this, but one block has more than ten networks, and the whole project has hundreds of blocks. It is wasteful and prone to mistakes, so I need to shorten it first.
Convert XML into text for AI to read
The converter follows the wires, starting at the coil and working backward toward the power rail. Contacts in series become AND, branches merging at an O box become OR, and it prints one line per network. Below is a shortened version that supports contacts, coils and O boxes, which is enough for typical interlock rungs. The version I actually use is longer because it also needs to support set/reset coils, edge detectors, timers and block calls.
# lad_to_text.py - แปลง SimaticML ของบล็อก LAD เป็นข้อความต่อ network (ฉบับย่อ: contact, coil, กล่อง O)
import sys
import xml.etree.ElementTree as ET
def ln(el): # ชื่อ tag แบบไม่สน namespace (v3 ใน V15.1)
return el.tag.rsplit('}', 1)[-1]
def operand(acc): # Access -> "DB_Act".Clamp.Lower.Out
names = [c.get('Name') for c in acc.iter() if ln(c) == 'Component']
return '"' + names[0] + '"' + ''.join('.' + n for n in names[1:])
def rungs(flg):
acc, part, opnd, src, rail = {}, {}, {}, {}, set()
for el in next(e for e in flg if ln(e) == 'Parts'):
if ln(el) == 'Access':
acc[el.get('UId')] = operand(el)
elif ln(el) == 'Part': # NC contact = มีลูกชื่อ Negated
part[el.get('UId')] = (el.get('Name'), any(ln(n) == 'Negated' for n in el))
for w in (e for e in flg.iter() if ln(e) == 'Wire'):
ident = [c.get('UId') for c in w if ln(c) == 'IdentCon']
pins = [(c.get('UId'), c.get('Name')) for c in w if ln(c) == 'NameCon']
if ident: # สายที่โยงตัวแปรเข้าขา operand
for uid, _ in pins:
opnd[uid] = acc[ident[0]]
elif any(ln(c) == 'Powerrail' for c in w):
rail.update(pins) # ขาที่ต่อกับราวไฟซ้าย
else: # ตัวแรกคือขา out ที่เหลือคือขา in ปลายทาง
for dst in pins[1:]:
src.setdefault(dst, []).append(pins[0][0])
def at(pin): # นิพจน์ที่มาถึงขา (uid, ชื่อขา)
if pin in rail:
return 'TRUE'
terms = [out(u) for u in src.get(pin, [])]
return terms[0] if len(terms) == 1 else '(' + ' OR '.join(terms) + ')'
def out(uid): # นิพจน์ที่ออกจาก part ตัวนี้
name, neg = part[uid]
if name == 'O': # กล่อง O = กิ่งขนาน
ins = sorted(k for k in src if k[0] == uid)
return '(' + ' OR '.join(at(k) for k in ins) + ')'
me = ('NOT ' if neg else '') + opnd[uid]
left = at((uid, 'in'))
return me if left == 'TRUE' else left + ' AND ' + me
for uid, (name, _) in part.items():
if name == 'Coil':
yield opnd[uid] + ' := ' + at((uid, 'in'))
root = ET.parse(sys.argv[1]).getroot()
units = [e for e in root.iter() if ln(e) == 'SW.Blocks.CompileUnit']
for n, cu in enumerate(units, 1):
title = ''
for mt in (e for e in cu.iter() if ln(e) == 'MultilingualText'):
if mt.get('CompositionName') == 'Title':
title = ' | '.join(t.text for t in mt.iter() if ln(t) == 'Text' and t.text)
print('[Network %d] %s' % (n, title))
flg = next((e for e in cu.iter() if ln(e) == 'FlgNet'), None)
for line in (rungs(flg) if flg is not None else ['(ไม่ใช่ LAD)']):
print(' ' + line)
Here is the output from the sample network above, along with one self-holding rung.
$ python lad_to_text.py FC_Station.xml
[Network 1] Clamp lower to valve
"Valve_Down" := "DB_Act".Clamp.Lower.Out
[Network 2] Run latch
"DO_Run" := ("DI_Start" OR "DO_Run") AND NOT "DI_Stop"
AI can read this format much like SCL, and I can review it faster than scrolling through networks one at a time in the editor. The full version takes an entire export folder and combines it into a single text file, so AI can read all 84 LAD blocks without opening the TIA screen at all.
The converter infers the structure from the wires. Complex rungs, such as boxes with multiple outputs or jumps, may not convert accurately. Use this text only for understanding and searching. Always confirm the actual location of an edit in the LAD editor, and never import back from the text. XML is what gets imported.
Add networks with a script and import with Override
On the writing side, I did not have AI write FlgNet XML by hand, because every UId and wire must match. A single mistake makes the import fail. I wrote a script that takes a short network description and generates the XML. The format is --net "ชื่อ network|coil|contact", with commas separating contacts in series and semicolons separating parallel branches that will be joined by an O box. A leading ! means an NC contact, and if the coil field contains CALL: followed by an FC name, it calls that FC.
# เพิ่ม 2 network ต่อท้าย FC_Station (จะกลายเป็น network 9 และ 10)
python add_lad_network.py FC_Station.xml FC_Station_new.xml \
--net "Clamp lower to valve|Valve_Down|DB_Act.Clamp.Lower.Out" \
--net "Clamp raise to valve|Valve_Up|!DB_Act.Clamp.Lower.Out"
# อ่านทวนด้วยตัวแปลงก่อน import ทุกครั้ง
python lad_to_text.py FC_Station_new.xml | tail -4
The script handles three things that are easy to get wrong by hand. First, UIds in the new network's FlgNet start at 21 and increase sequentially across both parts and wires. Second, the ID numbers for CompileUnit and multilingual text must not duplicate existing ones, so the script reads the highest value in the file and continues from there. Third, the network name must be XML-escaped before being written to the file. I ran into this myself: a network name containing <, > or & caused the entire file to fail to import because the name itself made the XML malformed.
I then import using the same command as in the verification step: find the group where the block already resides, then call Blocks.Import with ImportOptions.Override. My script always finds the block's existing group first and imports it there.
Renaming tags: PlcTag.Name is read-only
Step 3 of the verification was to rename two spare tags. I simply wrote $tag.Name = 'x' and got an exception, because the PlcTag Name property is read-only in V15.1. The approach that works is to save the original address and data type, delete the original tag, then create a new one at the same address. The comment must be set through Comment.Items, selecting the entry whose language is en-US.
function AllTables($g) { foreach ($t in $g.TagTables) { $t }; foreach ($s in $g.Groups) { AllTables $s } }
function FindTag($n) {
foreach ($t in (AllTables $sw.TagTableGroup)) { $x = $t.Tags.Find($n); if ($x) { return @($t, $x) } }
}
# เปลี่ยนชื่อ = เก็บ address/type -> ลบ -> สร้างใหม่ที่เดิม
$tbl, $tag = FindTag 'Spare_Q_01'
$addr = $tag.LogicalAddress; $typ = $tag.DataTypeName
$tag.Delete()
$new = $tbl.Tags.Create('Valve_Down', $typ, $addr)
foreach ($it in $new.Comment.Items) {
if ($it.Language.Culture.Name -eq 'en-US') { $it.Text = 'Clamp valve down' }
}
# ส่วน address เขียนได้ตรง ๆ ไม่ต้องลบสร้างใหม่
$tbl2, $tag2 = FindTag 'Valve_Up'
$tag2.LogicalAddress = '%Q10.1'
Deleting and recreating a tag has a side effect to watch for. If any code references the old tag name, it will now point to something that no longer exists. Before using this method, I need to search all the exported XML to confirm that no block references that name. A tag named as a spare is not necessarily unused.
Unexpected file end and the remaining source pitfalls
The actual editing work involved more than LAD. For new UDTs, DBs and FCs, I had AI write .udt, .db and .scl files, then imported them as external sources using GenerateBlocksFromSource. The first attempt failed with Unexpected file end, even though every file ended correctly.
The cause was that the files I supplied used LF line endings. TIA requires CRLF, so with LF, a comment starting with // swallowed the entire rest of the file. The fix is to convert to CRLF and write UTF-8 with a BOM every time before passing files to TIA.
param([Parameter(Mandatory)][string]$File) # .udt / .db / .scl
$esg = $sw.ExternalSourceGroup
$name = 'Imp_' + [IO.Path]::GetFileNameWithoutExtension($File)
$old = $esg.ExternalSources.Find($name); if ($old) { $old.Delete() }
# TIA ต้องการ CRLF + BOM: ถ้าเป็น LF comment // จะกลืนส่วนที่เหลือทั้งไฟล์
$txt = [IO.File]::ReadAllText($File) -replace "`r?`n", "`r`n"
$tmp = Join-Path $env:TEMP ([IO.Path]::GetFileName($File))
[IO.File]::WriteAllText($tmp, $txt, (New-Object Text.UTF8Encoding($true)))
$xsrc = $esg.ExternalSources.CreateFromFile($name, $tmp)
$xsrc.GenerateBlocksFromSource()
# DB ที่อิง UDT ยังเป็นของเก่าจนกว่าจะ compile
if ([IO.Path]::GetExtension($File) -in '.udt', '.db') {
$cc = $sw.GetType().GetMethod('GetService').MakeGenericMethod(
[Siemens.Engineering.Compiler.ICompilable]).Invoke($sw, $null)
$r0 = $cc.Compile()
"compile after type/DB: $($r0.State) errors=$($r0.ErrorCount)"
}
$xsrc.Delete()
I collected the remaining pitfalls in a table. I encountered every one of them, along with the messages shown.
| Symptom or message | Cause | Fix |
|---|---|---|
Exception when setting $tag.Name |
Name is read-only in V15.1 | Delete and recreate at the same address |
| Unexpected file end | Source file uses LF | Convert to CRLF and UTF-8 with a BOM |
| Tag ... not defined immediately after editing a UDT | DBs based on the UDT remain unchanged until compilation | Compile after every .udt and .db file |
Syntax error at .Return. |
Return is an SCL keyword | Write it as ."Return". |
| Invalid tag definition | Name extracted by regex has trailing whitespace | Strip whitespace before removing quotes |
| XML import fails | Network name contains < > & |
XML-escape the name before writing the file |
Parameter -Src gets overwritten |
A variable named $src is set in the same script; PowerShell is case-insensitive |
Give internal variables names distinct from the parameters |
| Know-how protected and ProDiag blocks are missing | They cannot be exported and are skipped | Treat this as normal and record which blocks cannot be read |
There is one more point that is not an error but needs to be understood: GenerateBlocksFromSource can directly overwrite FCs, DBs and UDTs with matching names, including changing an FC from LAD to SCL if the interface is the same. This is useful when I intend to rewrite an entire block, and equally dangerous when I give a file the wrong name and it collides with a machine block, because it does not ask at all.
Work from dependencies toward the blocks that reference them: UDT first, then DB, then the FC or FB being called, and finally the caller. Always compile after UDT and DB. If the order is wrong, I get messages saying a tag or member is not yet defined, even though it is in the next file.
The sequence I use every time
In summary, LAD in V15.1 can be edited with scripts, but both reading and writing must go through XML. The converted text is for reading, while what gets imported back is the XML with networks appended by the script. Before making any edits, I always complete one unchanged round trip and get a compile result of 0 errors.
My rule is to read the COMPILE state, errors and warnings lines in the log after every batch of edits before moving to the next step. Do not let a script run through several steps on its own and wait until the end to check, because an error in step two will surface as a strange message in step five, making the original cause hard to find.
What I have not done yet is add networks more complex than contacts and coils, such as timers or calculation boxes. My network generator supports only contacts in series, parallel branches and FC calls. For more complex work, I have AI write SCL in a separate block and call it from a LAD network. Feel free to extend this in whichever direction suits you. If I have missed anything in the explanation or encounter more pitfalls, I will come back and update it later.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first