I'm working with some xml and I'd like to clean it up before I parse it. What i'd like to do specifically, is take the data (example below) and match it on the string "<data>
" and then trim everything before it leaving the node in tact. Then I would match on the string "</data>
" and truncate everything after it, once again leaving the matched node in tact.
Turning this:
<dwml>
<head>
<child></child>
</head>
<data>
<child></child>
<child></child>
</data>
<more></more>
</dwml>
into this:
<data>
<child></child>
<child></child>
</data>
My Question:
While I am sure there is a way to do this, I don't know where to start. Could someone could point me in the right direction or better yet provide an example? I appreciate any help.
You can use componentsSeparatedByString to isolate your elements as follow:
let xmlString = "<dwml><head><child></child></head><data><child></child><child></child></data><more></more></dwml>"
func filterData(input: String) -> String {
return "<data>" + input.componentsSeparatedByString("<data>").last!.componentsSeparatedByString("</data>").first! + "</data>"
}
filterData(xmlString) // "<data><child></child><child></child></data>"
You can also use rangeOfString to find the range of your string:
func findData(input: String) -> String {
if let startIndex = input.rangeOfString("<data>", options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil)?.startIndex {
if let endIndex = input.rangeOfString("</data>", options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil)?.endIndex {
return input.substringWithRange(startIndex..<endIndex)
}
}
return ""
}
findData(xmlString) // "<data><child></child><child></child></data>"
来源:https://stackoverflow.com/questions/29836188/split-string-data-on-a-string-match