dataschema-table.mustache revision 11d2780adc5c17fefe1ea2d70c7e75ca6647c49c
0N/A<div class="intro">
4552N/A <p>DataSchema.XML can be used to retrieve data held in HTML TABLE elements.</p>
0N/A</div>
0N/A
0N/A<div class="example yui3-skin-sam">
0N/A {{>dataschema-table-source}}
0N/A</div>
0N/A
0N/A<p>DataSource.XML's `apply()` method supports passing in DOM nodes or document fragments. Use XPath strings to define data locations. In this example, we are retrieving data held in the rows of a TABLE element.</p>
0N/A
0N/A```
0N/AYUI().use("dataschema-xml", function(Y) {
0N/A var tableEl = Y.Node.getDOMNode(Y.one("#simple")),
0N/A schema = {
0N/A // Each record is held in a TR
0N/A resultListLocator: "tr",
0N/A // Note that the XPath indexes are 1-based!
0N/A resultFields: [
1472N/A {key:"beverage", locator:"td[1]"},
1472N/A {key:"price", locator:"td[2]"}
1472N/A ]
0N/A },
0N/A data_out = Y.DataSchema.XML.apply(schema, tableEl);
0N/A
1879N/A alert(data_out);
1879N/A});
1879N/A```
1879N/A
1879N/A<p>If the table has a THEAD element and/or multiple TBODY elements, special considerations must be taken to apply the schema to the appropriate collection of TR elements. In the following complex example we leverage the power of the Node API to</p>
0N/A
0N/A<ul>
0N/A <li>Access the contents of the THEAD to generate our schema dynamically;</li>
0N/A <li>and access only the TR elements contained in TBODY elements for data values, ignoring those TR elements in the THEAD.</li>
0N/A</ul>
2127N/A
2122N/A```
2122N/AYUI().use("dataschema-xml", function(Y) {
2127N/A // This function generates a schema based on contents of a TABLE element
2127N/A var getSchemaFromTableNode = function(tableNode) {
2122N/A var fields = [],
2122N/A // Each record is held in a TR
2122N/A schema = {resultListLocator:"tr"},
2127N/A // Each field name is held in a TH
2127N/A thList = tableNode.all("th");
2127N/A
2127N/A // Generate field definitions based on TH
2122N/A thList.each(function(thNode, i){
2127N/A // Note that the XPath indexes are 1-based!
0N/A fields.push({key:thNode.get("text"), locator:"td["+(i+1)+"]"});
0N/A });
3863N/A schema.resultFields = fields;
3863N/A return schema;
3863N/A };
3863N/A
3863N/A var tableNode = Y.one("#complex"),
0N/A // Generate schema dynamically
3863N/A schema = getSchemaFromTableNode(tableNode),
0N/A // Create a temporary TBODY container to hold all data TRs
3863N/A tbody = document.createElement("tbody"),
3863N/A tbodyContainer = document.createDocumentFragment().appendChild(tbody);
3863N/A
3863N/A // Grab each TR in a TBODY but don't include TRs from the THEAD
3863N/A Y.all("#complex tbody tr").each(function(trNode, i){
3863N/A // Cloning the TR keeps it in the document (optional)
3863N/A // Append each TR to the container
3863N/A tbodyContainer.appendChild(Y.Node.getDOMNode(trNode).cloneNode(true));
3863N/A })
3863N/A
0N/A var data_out = Y.DataSchema.XML.apply(schema, tbodyContainer);
0N/A
0N/A alert(data_out);
3863N/A});
0N/A```
0N/A