使用SWXMLHash解析模拟数据遇问题,寻求技术解决方案
Hey there! Let's work through your SWXMLHash issue. From what you've shared, your xmlData file contains hex-encoded XML content (like the 3c3f786d which translates to <?xm—the start of an XML declaration), but right now you're reading it directly as raw Data without decoding that hex string first. That's almost certainly why you're hitting parsing problems.
Here's how to fix this step by step:
1. Fix How You Read and Decode the File
Instead of reading the file directly into Data, you need to:
- Read the content as a hex string
- Clean up any whitespace (if your hex has spaces between bytes)
- Convert that hex string into actual XML
Datathat SWXMLHash can understand
Here's the updated code:
import SWXMLHash guard let fileURL = Bundle.main.url(forResource: "xmlData", withExtension: "") else { fatalError("Cannot load xmlData file from bundle") } do { // Read the file content as a UTF-8 string (since it's hex characters) let rawHexString = try String(contentsOf: fileURL, encoding: .utf8) // Remove any spaces or line breaks from the hex string let cleanedHex = rawHexString.replacingOccurrences(of: "\\s", with: "", options: .regularExpression) // Convert the cleaned hex string to valid XML Data guard let xmlData = Data(hexString: cleanedHex) else { fatalError("Failed to convert hex string to XML data") } // Now parse with SWXMLHash let xml = SWXMLHash.parse(xmlData) // Test with a sample parse (adjust based on your XML structure) if let rootName = xml.root?.element?.name { print("Successfully parsed XML root element: \(rootName)") } } catch { print("Error during process: \(error.localizedDescription)") }
2. Add a Data Extension for Hex String Conversion
Swift's native Data doesn't have a built-in way to convert hex strings, so add this extension to your Playground:
extension Data { init?(hexString: String) { let byteCount = hexString.count / 2 guard hexString.count % 2 == 0 else { return nil } var data = Data(capacity: byteCount) var index = hexString.startIndex while index < hexString.endIndex { let byteRange = index..<hexString.index(index, offsetBy: 2) guard let byte = UInt8(hexString[byteRange], radix: 16) else { return nil } data.append(byte) index = hexString.index(index, offsetBy: 2) } self = data } }
3. Double-Check Playground Resource Setup
Make sure your xmlData file is actually added to your Playground's resources:
- Open the Project Navigator (View > Navigators > Show Project Navigator)
- Drag your
xmlDatafile into the Resources folder of your Playground - Confirm the file's target membership is set to your Playground
If you skip this step, Bundle.main.url(forResource:) will return nil and trigger your fatal error.
内容的提问来源于stack exchange,提问作者koen

