问题
I have the following code to download a XBRL file into Google spreadsheet
function XBRLexplore() {
var ss = SpreadsheetApp.openById("0Aiy1DTQRndx6dFZLVDJfRnptbmRFUTM2S2lnUlRfWWd");
var Sheet = ss.getSheetByName("Sheet1"); // Activate sheet
var target = "http://www.sec.gov/Archives/edgar/data/867773/000086777313000052/spwr-20130630.xml";
var pageTxt = UrlFetchApp.fetch(target).getContentText();
var xbrl = Xml.parse(pageTxt,true).getElement()
var test=xbrl.getElements();
var output=[];
for (var i=0;i<test.length;i++){
var element=test[i]
var f=[element.contextref,element.id,element.unitref,element.decimals,e=element.Text]
output[i]=f;
}
Sheet.getRange(1,1,test.length,5).setValues(output);
}
this will drop about 1700 row by 5 columns into Google spreadsheet.
However, I want all the of sub elements in object "xbrl" added next to each of the elements.
For example: currently, row 1421 is the following data:
D2013Q2QTD Fact-456FCC569047499F03F61D8FBE559EC1 shares -3 133973000
I want it to look like this:
us-gaap WeightedAverageNumberOfDilutedSharesOutstanding D2013Q2QTD Fact-456FCC569047499F03F61D8FBE559EC1 shares -3 133973000
adding the namespace us-gaap
and WeightedAverageNumberOfDilutedSharesOutstanding
in the first 2 columns
it would be nice if for each element i can use some sort of getParent()
function then just stick it in the first 2 columns during the loop.
I'm trying to use the getNamespace()
for each element inside the loop, but it's giving me an error
var ff=element.getNamespace()
回答1:
I do not understand very well how you determine the nodes that need, however, after determining them, you can do the following for the first 2 columns you need:
...
var target = "http://www.sec.gov/Archives/edgar/data/867773/000086777313000052/spwr-20130630.xml";
var pageTxt = UrlFetchApp.fetch(target).getContentText();
var xbrl = XmlService.parse(pageTxt);
var element = xbrl.getRootElement().getChildren()[1420];
Logger.log(element.getNamespace().getPrefix()); // us-gaap
Logger.log(element.getName()); // WeightedAverageNumberOfDilutedSharesOutstanding
...
The new service is accessed using XmlService, in contrast to the old service which was simply called Xml.
UPDATE
My experience with XmlService is little, not too sure if you can use wildcards for the search of nodes, a very basic example and probably inefficient can be:
...
var ns = 'us-gaap';
var target = "http://www.sec.gov/Archives/edgar/data/867773/000086777313000052/spwr-20130630.xml";
var pageTxt = UrlFetchApp.fetch(target).getContentText();
var xbrl = XmlService.parse(pageTxt);
var elements = xbrl.getRootElement().getChildren();
var el, attr;
for (var element = 0, len = elements.length; element < len; ++element) {
el = elements[element];
if (el.getNamespace().getPrefix() === ns) {
/* YOUR CODE */
Logger.log(ns);
Logger.log(el.getName());
attr = el.getAttribute('contextRef');
if(attr) Logger.log(attr.getValue());
}
}
...
来源:https://stackoverflow.com/questions/18040867/google-script-xml-get-parent