XMLDocument を使って読み込んだ XML ファイルの子要素を取得し、属性などを読み取ろうと考えています。
XML が次のようになっていたとして、item の子要素である position. size を取得します。
XML
1<item> 2 <position x="100" y="200" /> 3 <size width="300" height="200" /> 4</item>
swift
1let item:XMLElement! = root.elements(forName: "item").first 2 3for child in item.children! { 4 switch(child.name!){ 5 case "position": 6 let x:Int! = Int((child.attribute(forName: "x")!.stringValue)!) 7 case "size": 8 let width:Int! = Int((child.attribute(forName: "width")!.stringValue)!) 9 default: break 10 } 11}
イメージとしては上のような形なのですが、item.children は XMLElement ではなく XMLNode です。そのため attribute() が利用できません。
item.elements() のほうが適切なのですが forName: を使う必要があり、名前を指定せずにすべての要素を取得する事ができません。
全ての子要素を XMLElement の形で取得する方法や、XMLNode を XMLElement に変換する方法なのは無いのでしょうか?
Xcode は 8.3 を使用しており、開発目的は Mac 用のデスクトップアプリケーションです。
よろしくお願い致します。
あなたの回答
tips
プレビュー