我正在尝试从Goodreads xml文件中获取ID名称。 我正在尝试返回所有架子名称ID,并希望在一行中用“,”替换新行。
这就是我所要克服的问题
function GetSHELVES(ID) {
book = encodeURIComponent(ID);
var url = 'https://www.goodreads.com/book/show/' + ID + '.xml?key=REDACTED';
var response = UrlFetchApp.fetch(url).getContentText();
var xml = XmlService.parse(response);
var root = xml.getRootElement();
var BookSHELVES = root
.getChild('book')
.getChild('popular_shelves')
.getAttribute('shelf name')
.getValue();
Logger.log(BookSHELVES);
return BookSHELVES;
}
这是示例XML工作表
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<GoodreadsResponse>
<Request>
<authentication>true</authentication>
<key>...</key>
<method>
<![CDATA[ book_show ]]>
</method>
</Request>
<book>
<popular_shelves>
<shelf name="to-read" count="437"/>
<shelf name="fantasy" count="31"/>
<shelf name="audible" count="19"/>
<shelf name="urban-fantasy" count="16"/>
<shelf name="audiobook" count="15"/>
<shelf name="audiobooks" count="12"/>
<shelf name="audio-books" count="10"/>
<shelf name="audio" count="9"/>
<shelf name="alternate-history" count="7"/>
</popular_shelves>
</book>
</GoodreadsResponse>
任何帮助将不胜感激
答案 0 :(得分:0)
如果我的理解是正确的,那么该修改如何?
root.getChild("book").getChild("popular_shelves")
是正确的。但是popular_shelves
有几个shelf
。因此,它使用shelf
检索了所有getChildren()
。name="###"
可以检索getAttribute("name").getValue()
。请进行以下修改,然后重试。
从:var BookSHELVES = root
.getChild('book')
.getChild('popular_shelves')
.getAttribute('shelf name')
.getValue();
至:
var popularShelves = root.getChild("book").getChild("popular_shelves").getChildren();
var BookSHELVES = popularShelves.map(function(shelf) {return shelf.getAttribute("name").getValue()}).join(",");
结果:
to-read,fantasy,audible,urban-fantasy,audiobook,audiobooks,audio-books,audio,alternate-history
response
是您问题中的XML值。如果这不是您想要的,对不起。