ActionScriptによるXMLデータ処理(2) - XMLデータの構築
Copyright© N/A
XMLオブジェクトやXMLSocketを用いてサーバーと通信を行う際に送信するXMLデータを構築するActionScriptのコード例を紹介する。以下のような簡単なXMLを構築する場合を考える。
<?xml version="1.0" encoding="UTF-8" ?> <data> <item id="item1">・・・・</item> <item id="item2">・・・・</item> </data>
XMLに記述すべきツリーのデータ数が多い場合には、XML解析と同様の手順で再帰関数を用い、逆の操作を行い構築する。
関連項目:ActionScriptによるXML読み込み・解析
XMLの構築(1)
XMLを構築する最も簡易な方法は、XMLを全てテキストとして作りそれをXMLオブジェクトに読み込ませる方法である。テキストに含まれるXMLセーフではないキャラクタについては、エンティティ変換を行う必要がある。
function createDataXML() {
var strXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
strXML += "<data>";
strXML += "<item id=\"item1\">" + procEntities(strValue1) + "</item>";
strXML += "<item id=\"item2\">" + procEntities(strValue2) + "</item>";
strXML += "</data>";
var infoXML = new XML(strXML);
return infoXML;
}
function procEntities(strValue) {
strValue = strValue.split("&").join("&");
strValue = strValue.split("\"").join(""");
strValue = strValue.split("'").join("'");
strValue = strValue.split("<").join("<");
strValue = strValue.split(">").join(">");
return strValue;
}
XMLの構築(2)
上記と同じXMLをXMLオブジェクトに用意されたメソッドを使用してまともに構築すると次のようになる。この場合、テキストのエンティティ変換は自動的に行われるため、前もって処理しておく必要はない。
function createDataXML() {
var infoXML = new XML();
var infoRootXML = new XML();
var infoItemXML = new XML();
var infoTextXML = new XML();
infoXML.xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
var infoRoot = infoRootXML.createElement("data");
infoXML.appendChild(infoRoot);
var infoItem1 = infoItemXML.createElement("item");
infoItem1.appendChild(infoTextXML.createTextNode(strValue1));
infoItem1.attributes["id"] = "item1";
infoRoot.appendChild(infoItem1);
var infoItem2 = infoItemXML.createElement("item");
infoItem2.appendChild(infoTextXML.createTextNode(strValue21));
infoItem2.attributes["id"] = "item2";
infoRoot.appendChild(infoItem2);
return infoXML;
}Hidden gems
- Online Slots UK
- Meilleur Casino En Ligne Fiable
- Non Gamstop Casinos
- UK Casinos Not On Gamstop
- UK Casino Sites Not On Gamstop
- Casino Sites Not On Gamstop
- Casino Not On Gamstop
- Casinos Not On Gamstop
- Casino Not On Gamstop
- Betting Sites UK
- Non Gamstop Casino Sites UK
- Slots Not On Gamstop
- Brand New Non Gamstop Casinos