1_AEXML_XML的 生成 与 解析

该文章展示了如何在iOS应用中使用AEXML库来解析和生成XML数据。首先,通过CocoaPods引入AEXML库,然后演示了读取XMLExample.xml文件并提取其中的cats和dogs信息。接着,文章详细解释了如何遍历和过滤XML节点,以及如何创建新的XML结构。
摘要由CSDN通过智能技术生成
platform :ios, '13.0'
use_frameworks!

target 'DemoApp' do
    source 'https://github.com/CocoaPods/Specs.git'
    pod 'AEXML'
end
  • XMLExample.xml
<?xml version="1.0" encoding="utf-8"?>
<animals>
<cats>
<cat breed="Siberian" color="lightgray">Tinna</cat>
<cat breed="Domestic" color="darkgray">Rose</cat>
<cat breed="Domestic" color="yellow">Caesar</cat>
<cat></cat>
</cats>
<dogs>
<dog breed="Bull Terrier" color="white">Villy</dog>
<dog breed="Bull Terrier" color="white">Spot</dog>
<dog breed="Golden Retriever" color="yellow">Betty</dog>
<dog breed="Miniature Schnauzer" color="black">Kika</dog>
</dogs>
</animals>
  • XML的解析:
import UIKit
import AEXML
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        yeTyeXML()
    }
    
    func yeTyeXML(){
        // 加载文件, 并转成Data二进制数据:
        guard let xmlPath = Bundle.main.path(forResource: "XMLExample", ofType: "xml"),
              let data = try? Data(contentsOf: URL(fileURLWithPath: xmlPath)) else { return }
        
        do
        {
            let xmlDoc = try AEXMLDocument(xml: data, options: AEXMLOptions())
            print("---XML格式的完整原数据:\(xmlDoc.xml)--")
            
            print(xmlDoc.root["cats"]["cat"].count) //4
            print(xmlDoc.root["cats"]["cat"].attributes["breed"]!) // Siberian;
            print(xmlDoc.root["cats"]["cat"].xmlCompact) //<cat breed="Siberian" color="lightgray">Tinna</cat>
            
            for child in xmlDoc.root.children
            {
                print("---XML节点名:child.name:\(child.name)--")
                //---XML节点名:child.name:cats--
                //---XML节点名:child.name:dogs--
            }
            
            print("-----------------------------")
            print(xmlDoc.root["cats"]["cat"].value as Any)       //Optional("Tinna")
            print(xmlDoc.root["cats"]["cat"].string)             //Tinna
            print(xmlDoc.root["dogs"]["dog"].last?.value as Any) //Optional("Kika")
            print(xmlDoc.root["dogs"].children[2].string)        //Betty
            
            print("--------------all---------------")
            if let cats = xmlDoc.root["cats"]["cat"].all
            { // 遍历节点 的值:
                for cat in cats
                {
                    if let name = cat.value
                    {
                        print(name) // Tinna, Rose, Caesar ;
                    }
                }
            }
            
            print("---------------withValue--------------")
            if let cats = xmlDoc.root["cats"]["cat"].all(withValue: "Tinna")
            { // 当 值==Tinna 的节点:
                for cat in cats
                {
                    print(cat.string) //Tinna
                }
            }
            print("-------------withAttributes----------------")
            
            if let cats = xmlDoc.root["cats"]["cat"].all(withAttributes: ["breed" : "Domestic", "color" : "yellow"])
            { // 当 breed == Domestic, color == yellow, 的节点:
                for cat in cats
                {
                    print(cat.string) //Caesar
                }
            }
            
            print("--------------attributes---------------")
            for dog in xmlDoc.root["dogs"]["dog"].all!
            {
                if let color = dog.attributes["color"]
                { // 按 color条件 筛选:
                    if color == "white"
                    {
                        print(dog.string) // Villy, Spot ;
                    }
                }
            }
        }
        catch
        {
            print("\(error)")
        }
    }
}
  • 生成XML格式的数据:
import UIKit
import AEXML
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        yeTyeXMLWrite()
    }
    
    func yeTyeXMLWrite(){
        let soapRequest = AEXMLDocument()
        let attributes = ["xmlns:xsi" : "https://www.baidu.com/2001/XMLSchema-instance",
                          "xmlns:xsd" : "https://www.baidu.com/2001/XMLSchema"]
        
        let envelope = soapRequest.addChild(name: "soap:Envelope", attributes: attributes)
        let employees = envelope.addChild(name: "Employees")
        let managers = employees.addChild(name: "Managers")
        managers.addChild(name: "Manager", attributes:["Name":"Jerry", "age":"40"])
        managers.addChild(name: "Manager", attributes:["Name":"Peter", "age":"44"])
        
        let engineers = employees.addChild(name: "Engineers")
        engineers.addChild(name: "Engineer", attributes:["Name":"Bill", "age":"29"])
        engineers.addChild(name: "Engineer", attributes:["Name":"Somus", "age":"31"])
        
        print("---生成的XML格式数据:\(soapRequest.xml)--")
        /*
         <?xml version="1.0" encoding="utf-8" standalone="no"?>
         <soap:Envelope xmlns:xsd="https://www.baidu.com/2001/XMLSchema" xmlns:xsi="https://www.baidu.com/2001/XMLSchema-instance">
             <Employees>
                 <Managers>
                     <Manager Name="Jerry" age="40" />
                     <Manager Name="Peter" age="44" />
                 </Managers>
                 <Engineers>
                     <Engineer Name="Bill" age="29" />
                     <Engineer Name="Somus" age="31" />
                 </Engineers>
             </Employees>
         </soap:Envelope>
         */
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值