XMLドキュメントをFlexGridコントロールの階層化データソースとして使用できます。
DOMParserオブジェクトを使用して、XML文字列をドキュメントオブジェクトとして解析します。次にドキュメントをループ処理して、"category"項目から成る配列を構築し、それぞれの項目に"products"配列を挿入します。
// データソースとして使用するXML文字列を取得します
function getXml() {
return `
<categories>
<category id="0" name="飲料">
<product id="0" name="果汁100%オレンジ" price="3600" />
<product id="1" name="果汁100%グレープ" price="2400" />
<product id="2" name="果汁100%レモン" price="2700" />
<product id="3" name="果汁100%ピーチ" price="3700" />
<product id="4" name="コーヒーマイルド" price="3200" />
</category>
<category id="1" name="調味料">
<product id="10" name="ホワイトソルト" price="2400" />
<product id="11" name="ブラックペッパー" price="3600" />
<product id="12" name="ピュアシュガー" price="3900" />
<product id="13" name="うまい素" price="1100" />
<product id="14" name="ピュアデミグラスソース" price="3100" />
</category>
</categories>`;
}
// XMLドキュメントを解析して配列を生成します
function getProductsByCategory() {
var items = [],
parser = new DOMParser(),
xml = getXml(),
doc = parser.parseFromString(xml, 'application/xml');
// カテゴリを取得します
var categories = doc.querySelectorAll('category');
for (var c = 0; c < categories.length; c++) {
var category = categories[c];
items.push({
id: parseInt(category.getAttribute('id')),
name: category.getAttribute('name'),
products: []
});
// このカテゴリの商品を取得します
var products = category.querySelectorAll('product');
for (var p = 0; p < products.length; p++) {
var product = products[p];
items[items.length - 1].products.push({
id: parseInt(product.getAttribute('id')),
name: product.getAttribute('name'),
price: parseFloat(product.getAttribute('price'))
})
}
}
// 完了
return items;
}
この配列がitemsSourceとして使用され、childItemsPathプロパティを使用して、各カテゴリの商品がツリーとして表示されます。
import * as wjGrid from '@mescius/wijmo.grid';
var theGrid = new wjGrid.FlexGrid('#theGrid', {
autoGenerateColumns: false,
columns: [
{ binding: 'name', header: '名前', width: '3*' },
{ binding: 'id', header: 'ID', dataType: 'String', width: '*' },
{ binding: 'price', header: '単価', format: 'n2', dataType: 'Number', width: '*' },
],
headersVisibility: 'Column',
childItemsPath: 'products',
treeIndent: 25,
itemsSource: getProductsByCategory()
});