我一直在嘗試決議 xml 的某些部分,包括 CDATA,但我不明白為什么 cdata 根本沒有顯示。我一直在嘗試用 SWXMLHASH 解決這個問題
下面是xml
<DOC title=\"Effect\" type=\"EE\">
<SECTION title=\"\">
<ARTICLE title=\"1. Main Effect\">
<PARAGRAPH tagName=\"p\" textIndent=\"0\" marginLeft=\"0\">
<![CDATA[Pain due to several diseases]]>
</PARAGRAPH>
</ARTICLE>
<ARTICLE title=\"2. Indications\">
<PARAGRAPH tagName=\"p\" textIndent=\"0\" marginLeft=\"0\">
<![CDATA[Rheuatism]]>
</PARAGRAPH>
</ARTICLE>
</SECTION>
</DOC>
下面是我的代碼
import SwiftUI
import SWXMLHash
struct Article : XMLIndexerDeserializable, Identifiable, Hashable {
let id = UUID()
let title : String
let paragraph : [String]
enum CodingKeys: String, CodingKey {
case article = "ARTICLE"
case paragraph = "PARAGRAPH"
}
static func deserialize(_ node: XMLIndexer) throws -> Article {
return try Article (
title: node.value(ofAttribute: "title"),
paragraph: node["ARTICLE"]["PARAGRAPH"].value()
)
}
}
struct MyDrug: View {
@State var drugNameSearch = [DrugNameSearch]()
var body: some View {
GeometryReader{geometry in
ForEach(drugNameSearch, id: \.self){item in
VStack(alignment: .leading, spacing: geometry.size.height/50){
let xmlEffect = item.effect //this is xml same as above
let xml = XMLHash.config { config in
config.shouldProcessLazily = true
}.parse(xmlEffect)
let effectsArticle: [Article] = try! xml["DOC"]["SECTION"]["ARTICLE"].value()
ForEach(effectsArticle, id: \.self){
Text($0.title)
.foregroundColor(Color("tabBarBackground"))
.font(.body)
ForEach($0.paragraph, id: \.self){i in
Text(i)
.foregroundColor(Color("tabBarBackground"))
.font(.body)
}
}
}
}
}
}
}
使用該代碼,文章標題正確,但沒有段落資料,也沒有任何錯誤。請給我一些建議。。
uj5u.com熱心網友回復:
主要問題是,在您的自定義Article型別中,當檢索 PARAGRAPH 的值時,它應該是:paragraph: node["PARAGRAPH"].value()
這是因為該節點已被 ARTICLE 索引,因此您不必指定該索引。所以,整個文章型別看起來像:
struct Article : XMLIndexerDeserializable, Identifiable, Hashable {
let id = UUID()
let title : String
let paragraph : [String]
enum CodingKeys: String, CodingKey {
case article = "ARTICLE"
case paragraph = "PARAGRAPH"
}
static func deserialize(_ node: XMLIndexer) throws -> Article {
return try Article (
title: node.value(ofAttribute: "title"),
paragraph: node["PARAGRAPH"].value()
)
}
}
要檢查的另一件事......如果不會超過一個段落,那么可以將其定義為String而不是[String].
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/406582.html
標籤:
