XLIFFKit

一个用于解析和修改 XLIFF 文件的 Swift 框架。

一个 XLIFF 文件示例

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xliff version="1.2">
    <file original="Sample/en.lproj/Localizable.strings" source-language="en" target-language="it">
        <body>
            <trans-unit id="common.greeting.hello" xml:space="preserve">
                <source>Hello</source>
                <target>Ciao</target>
                <note>Casual greeting</note>
            </trans-unit>
            <trans-unit id="How are you?" xml:space="preserve">
                <source>How are you?</source>
                <target>Come stai?</target>
                <note></note>
            </trans-unit>
        </body>
    </file>
    <file original="AnotherSample/en.lproj/Localizable.string" source-language="en" target-language="it">
        <body>
            <trans-unit id="Thank you" xml:space="preserve">
                <source>Thank you</source>
                <target>Grazie</target>
            </trans-unit>
            <trans-unit id="You’re welcome" xml:space="preserve">
                <source>You’re welcome</source>
                <target state="needs-review-translation">Prego</target>
                <note>Casual thanks</note>
            </trans-unit>
            <trans-unit id="How old are you?" xml:space="preserve">
                <source>How old are you?</source>
            </trans-unit>
        </body>
    </file>
</xliff>

用法

导入框架

import XLIFFKit

打开 XLIFF 文件

let document = try XLIFFDocument(data: data)

遍历 XLIFF 的翻译单元

for file in document.files {
  for translationUnit in file.body.translationUnits {
    print(translationUnit.source, translationUnit.target)
  }
}

XLIFFTranslationUnit 是什么

public struct XLIFFTranslationUnit: Hashable {
  public let uuid: UUID
  public let id: String
  public let source: String
  public let note: String?
  public var target: String?
  public var state: XLIFFState?
}

修改翻译单元

let file = document.files[0]
var translationUnit = file.body.translationUnits[0]

translationUnit.target = "New value"
translationUnit.state = .needsReviewTranslation

document.updateTranslationUnit(forFileUUID: file.uuid, to: translationUnit)

UUID 不存在于 XLIFF 中;它为文件和翻译单元生成。它用于引用和跟踪文档中的元素。

进行修改后,document.hasUnsavedChanges 将变为 true。调用 document.commitUnsavedChanged() 以将更改写回底层的 XML 文档。

保存更改

if document.hasUnsavedChanges {
  document.commitUnsavedChanges()
}

let newData = document.xmlData()