Swift 4-使用struct解析XML文件

时间:2018-07-13 17:36:27

标签: swift xml

我的第一个带有XML解析的Swift App可以工作。我想清除代码。所以我用相同的应用程序开始了一个新项目。

这是我的结构

 Option Explicit

 Dim KeywordSearch As Range 
 Dim NoiseWords As Range 
 Dim cell As Range
 Dim NoiseWord As Range 
 Dim i As Long , j As Long 
 Dim NWTable As ListObject 
 Dim NewRow As ListRow 
 Dim SCTable As ListObject

 Sub Highlight()
     Dim s As String
     Dim offset As Integer
     Dim word As String

     Worksheets("Keyword Search").Activate
     Set KeywordSearch = ActiveSheet.Range("B3", Range("B3").End(xlDown))
     Set NWTable = ActiveSheet.ListObjects("Table1")
     Set SCTable = ActiveSheet.ListObjects("SC")

     Worksheets("Noise Words").Activate
     Set NoiseWords = ActiveSheet.Range("B2", Range("B2").End(xlDown))

     ' clear table
     On Error Resume Next

     NWTable.DataBodyRange.ClearContents
         Dim r As Range
         Set r = NWTable.Range.Rows(1).Resize(2)
         NWTable.Resize r

     SCTable.DataBodyRange.ClearContents
         Dim t As Range
         Set t = SCTable.Range.Rows(1).Resize(2)
         SCTable.Resize t

     On Error GoTo 0

     For Each cell In KeywordSearch
         s = cell.Value
         offset = 1

         cell.Interior.Color = vbWhite
         cell.Characters.Font.Color = vbBlack

         Do

         'Replace smart quotes
         For j = 1 To Len(s)
             cell.Characters(j, 1).Text = Replace(cell.Characters(j, 1).Text, Chr(147), """")
             cell.Characters(j, 1).Text = Replace(cell.Characters(j, 1).Text, Chr(148), """")

             ' Find the special characters and add to SpecialCharacters list
             If InStr("""!@#$%&'+,.:;<=>?^`{|}~*()/", Mid(s, j, 1)) > 0 Then
                     cell.Characters(j, 1).Font.Color = vbRed
                     Set NewRow = SCTable.ListRows.Add
                     NewRow.Range.Cells(1, 1) = Mid(s, j, 1)

             ' Replace with spaces
                     Mid(s, j, 1) = " "
                     End If
           Next

             ' Find the next space
             i = InStr(offset, s, " ")

             ' If no spaces left then go to end
             If i = 0 Then
                     i = Len(s) + 1
             End If

             ' Extract the word
             word = LCase(Mid(s, offset, i - offset))

                ' Capitalize AND OR NOT
                 If word = "and" Or word = "not" Or word = "or" Then
                     For j = 1 To Len(word)
                         cell.Characters(offset + j - 1, 1).Text = UCase(Mid(word, j, 1))
                     Next
                 End If

              ' Special case to capitalize w/
                If word = "w/" And i < Len(s) Then
                     cell.Characters(i - 2, 2).Text = UCase(word)
                End If

             ' Is the word in the NoiseWord list?
             For Each NoiseWord In NoiseWords
                 If NoiseWord.Value = word Then
                 ' Highlight word
                 cell.Characters(offset, i - offset).Font.Color = 5287936

                 ' Add to NWList
                 Set NewRow = NWTable.ListRows.Add
                 NewRow.Range.Cells(1, 1) = word

                 Exit For
             End If
             Next

             offset = i + 1
             Loop Until i > Len(s)
     Next

     With NWTable.Sort
         .SortFields.Clear
         .SortFields.Add Key:=Range("Table1[[#All],[Noise Words]]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
         .Apply
     End With

     NWTable.Range.RemoveDuplicates Columns:=1, Header:=xlYes

     SCTable.Range.RemoveDuplicates Columns:=1, Header:=xlYes

     Worksheets("Keyword Search").Activate

 End Sub

XML解析器

struct Bereich {
    var name = ""
    var wert = ""
    var status = ""
    var symbol = ""
}

代码将一直运行到这里

class ParseXML: NSObject, XMLParserDelegate {
    var eName : String = ""

    var vName : String = ""
    var vWert : String = ""
    var vStatus : String = ""
    var vSymbol : String = ""

    var xmlAsArray = [Bereich]()

    func startParsing(){
        getXMLDataFromServer()
    }

    func getXMLDataFromServer(){
        let url = NSURL(string: "https://*******************")

        let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in
            if data == nil {
                print("dataTaskWithRequest error: \(String(describing: error?.localizedDescription))")
                return
            }

            let parser = XMLParser(data: data!)
            parser.delegate = self
            parser.parse()
        }

        task.resume()
    }

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {

        eName = elementName
        if elementName == "param"{
            print("Started parsing")
        }
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {

        let foundedChar = string.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)

        switch eName {
        case "name": vName = foundedChar
        case "Wert": vWert = foundedChar
        case "Status": vStatus = foundedChar
        case "Symbol": vSymbol = foundedChar
        default: break
        }
    }

这部分代码似乎无法正常工作。 我无法弄清楚为什么它没有将XML的元素解析为结构和数组。

编辑:

我知道了。添加在xml标记中找到的每个字符必须为“ + =”。

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if eName == "param"{
        var myBereich = Bereich()
        myBereich.name = vName
        myBereich.wert = vWert
        myBereich.status = vStatus
        myBereich.symbol = vSymbol
        xmlAsArray.append(myBereich)
    }

    print("Parsing ended")
}

0 个答案:

没有答案