Using LIBXML2 in Swift

Source: Internet
Author: User
Tags xpath

////Main.swift//C150805_LIBXML2R2//  http://git.oschina.net/yao_yu/Swift2015/tree/master/C150805_libxml2r2?dir=1&filepath=c150805_libxml2r2&oid=f80a7498226526b991e7913298c15cd38480aea5&sha= c073af33d0534a10098bb8fcc0706c2fd489dc3f////Created by Yao_yu on 15/8/5.//copyright©2015 year Yao_yu. All rights reserved.//Import Foundation/*----------Extension----------*/extension nsstring{convenience init?(urlstring:string, encoding:nsstringencoding) {Let URL= Nsurl (string: urlstring) Do {            TrySelf.init (contentsofurl:url!, Encoding:encoding)} Catch{}}}extension String {init? (XmlcharChar: unsafepointer<xmlchar>) {self.init ()if Char!=Nil { self= String.fromcstring (Unsafepointer<cchar> (Char))!        }    }}/*----------XML node----------*/classXMLNode {var xmldoc:xmldocptr=nil var xmlnode:xmlnodeptr=Nil init (node:xmlnodeptr, document:xmldocptr) {Self.xmlnode=node Self.xmldoc=Document} convenience init (document:xmldocptr) {self.init (Node:xmldocgetrootelement (document), doc ument:document)} lazy var rawcontent:string? = {       returnxmlnodegetcontent (Self.xmlnode)//return xmlnodegetstring (Self.xmldoc, XmlNode:self.xmlNode)} () lazy var children:[xmlnode]= {        returnself.xmlnodes2xmlnodes (Xmlnodegetchildren (Self.xmlnode))} () lazy var attributes: [string:string]= {        returnxmlnodegetattributes (Self.xmlnode)} () subscript (key:string)String? {        returnAttributes[key]}PrivateFunc xmlnodes2xmlnodes (Nodes:[xmlnodeptr])[XMLNode] {var xmlNodes=[XMLNode] () forNodeinchnodes{xmlnodes.append (XMLNode (Node:node, Document:xmldoc))}returnXmlNodes//The following code is thrown: Command failed due to Signal:abort trap:6//return nodes.map{[unowned Self] in XMLNode (node:$0, Document:self.xmlDoc)}}}extension XMLNode {func xPath (xpath:string)-[XMLNode] {returnxmlnodes2xmlnodes (Xmlfindxpath (Self.xmldoc, Xpath:xpath)}}/*----------libxml2 Read tool function----------*/func xmlnodegetstring (doc:xmldocptr, xmlnode:xmlnodeptr)String?{Let Contentchars= Xmlnodelistgetstring (Doc, XmlNode,1)    ifContentchars = = Nil {returnNil} let contentstring=String (xmlchar:contentchars) free (Contentchars) assert (contentstring! = Nil,"xmlnodegetstring: Value conversion not successful")    returncontentstring}func xmlnodegetcontent (xmlnode:xmlnodeptr)String?{Let Contentchars=xmlnodegetcontent (XmlNode)ifContentchars = = Nil {returnNil} let contentstring=String (xmlchar:contentchars) free (Contentchars) assert (contentstring! = Nil,"Xmlnodegetcontent: Value conversion not successful")    returncontentstring}func Xmlnodegetchildren (xmlnode:xmlnodeptr)-[xmlnodeptr] {var children=[Xmlnodeptr] () forvar childnodepointer =XmlNode.memory.children; Childnodepointer!=Nil; Childnodepointer=ChildNodePointer.memory.next {ifXmlnodeistext (childnodepointer) = =0{children.append (Childnodepointer)}}returnchildren}func xmlnodegetattributes (xmlnode:xmlnodeptr)-[string:string] {var result:[string:string]=[string:string] () forvar attribute:xmlattrptr =xmlNode.memory.properties; Attribute!=Nil; Attribute=Attribute.memory.next {ifLet key:string =String (XMLChar:attribute.memory.name) {ifLet value:string =xmlnodegetcontent (Attribute.memory.children) {Result[key]=Value}Else{Result[key]=""            }        } Else{print (">>>>>>>>>>>>>>>>>>>>>>>> Error:", String (XMLChar:attribute.memory.name))) }    }    returnResult}func Xmlnodegetattribute (xmlnode:xmlnodeptr, key:string)String? {     forvar attribute:xmlattrptr =xmlNode.memory.properties; Attribute!=Nil; Attribute=Attribute.memory.next {ifKey = =String (XMLChar:attribute.memory.name) {returnxmlnodegetcontent (Attribute.memory.children)}} returnNil}func Xmlfindxpath (xmldoc:xmldocptr, xpath:string)-[xmlnodeptr] {let Xpathcontext=Xmlxpathnewcontext (xmldoc)ifXpathcontext = =Nil {return[]} xPathContext.memory.node=Nil Let Xpathobject= Xmlxpathevalexpression (unsafepointer<xmlchar> (xpath.cstringusingencoding (NSUTF8StringEncoding)!), Xpathcontext) Xmlxpathfreecontext (xpathcontext)ifXpathobject = =Nil {return[]} let NodeSet=XPathObject.memory.nodesetvalifNodeSet = = Nil | | NodeSet.memory.nodeNr = =0|| NodeSet.memory.nodeTab = =Nil {xmlxpathfreeobject (xpathobject)return[]} var resultnodes=[Xmlnodeptr] () forIinch 0.. <Int (nodeSet.memory.nodeNr) {resultnodes.append (nodeset.memory.nodetab[i])} xmlxpathfreeobject (XPat Hobject)returnresultnodes}func xmlreadnsdata (data:nsdata?, encoding:nsstringencoding = nsutf8stringencoding, Isxml:bool =false)-Xmldocptr?  {    ifLet data =Data {Let CBuffer= unsafepointer<cchar>(data.bytes) let CSize=CInt (data.length)////Let cfencoding = cfstringconvertnsstringencodingtoencoding (encoding)//Let cfencodingasstring:cfstringref = Cfstringconvertencodingtoianacharsetname (cfencoding)//Let cencoding:unsafepointer<cchar> = Cfstringgetcstringptr (cfencodingasstring, CFStringEncoding (0))        ifisxml {Let options=CInt (Xml_parse_recover.rawvalue)returnxmlreadmemory (CBuffer, cSize, nil, nil, options)}Else{Let options= CInt (Html_parse_recover.rawvalue | Html_parse_nowarning.rawvalue |html_parse_noerror.rawvalue)returnhtmlreadmemory (CBuffer, cSize, nil, nil, options)}} returnNil}let gb18030_2000_encoding=cfstringconvertencodingtonsstringencoding (cfstringencoding (CFStringEncodings.GB_18030_2000.rawValue))/*----------Test Code----------*/classCelapsetime {var starttime:nsdate var prompt:string var unsed:bool=falseInit (prompt:string) {self.starttime=nsdate () self.prompt=prompt} var newprompt:string {return "\ (Prompt) Time: \ (NSDate (). Timeintervalsincedate (startTime))"    }}func Testparsesina () {var surl:string var encoding:uint (surl,encoding)= ("http://www.baidu.com", nsutf8stringencoding) print ("<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<<<<<<<\ (sURL)") var timer= Celapsetime (prompt:"reading Web pages")    //Let scontent = NSString (Urlstring:surl, encoding:encoding)var scontent:nsstring? =Nil Do{        TryScontent = NSString (contentsoffile:"/volumes/data/document/test/sample.txt", Encoding:nsutf8stringencoding)} Catch{} print (timer.newprompt) let STimer1=timer.newprompt Timer= Celapsetime (prompt:"Data Parsing")        ifLet doc = Xmlreadnsdata (scontent?. Datausingencoding (nsutf8stringencoding)) {Let RootNode=XMLNode (document:doc) let Findnodes= Rootnode.xpath ("//div")         forChildnodeinchFindnodes {autoreleasepool{Let _=(Childnode.attributes, childnode.rawcontent)}//if let content = childnode.rawcontent {//Print (content)//            }} print (Findnodes.count)} print (STimer1) print (timer.newprompt)}testparsesina ()

Using LIBXML2 in Swift

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.