嘗試訪問第一項的子項時為空結果。我正在使用谷歌應用腳??本。
function parseXml() {
var url = 'https://example.xml';
var xml = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement();
var channel = root.getChild('channel');
var items = channel.getChildren('item');
Logger.log(items[1].getValue());
Logger.log(items[1].getChildren())
Logger.log(items[1].getChild('g:id'))
}
輸出:
5:37:46 PM Notice Execution started
5:37:57 PM Info 09771332150202100001A&C Ainsworth Wines - A&C Ainsworth Wines - 2021
5:37:57 PM Info [[Element: <g:id [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:title [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:description [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:link [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:image_link [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:availability [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:price [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:item_group_id [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:brand [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:gender [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:condition [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:google_product_category [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:product_type [Namespace: http://base.google.com/ns/1.0]/>], [Element: <g:spec [Namespace: http://base.google.com/ns/1.0]/>], [Element: <quantity/>], [Element: <option_values/>]]
5:37:57 PM Info null
5:37:58 PM Notice Execution completed
最后,XML 示例。抱歉,我無法分享
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<item>
<g:id>09771332140202100001</g:id>
<g:title>A&C Ainsworth Wines - A&C Ainsworth Wines - 2021</g:title>
<g:description></g:description>
</item>
uj5u.com熱心網友回復:
我相信您當前的問題和目標如下。
Logger.log(items[1].getChild('g:id'))回傳null。- 您想通過修改腳本從
<g:id>###</g:id>in 中檢索值。item
當我看到您在腳本中顯示 XML 和腳本時,我認為需要使用命名空間。當這反映在您的腳本中時,它變成如下。
從:
Logger.log(items[1].getChild('g:id'))
至:
Logger.log(items[1].getChild('id', XmlService.getNamespace("http://base.google.com/ns/1.0")))
或者
Logger.log(items[1].getChild('id', XmlService.getNamespace("g", "http://base.google.com/ns/1.0")))
或者
Logger.log(items[1].getChild('id', XmlService.getNamespace("http://base.google.com/ns/1.0")).getValue())
或者
Logger.log(items[1].getChild('id', XmlService.getNamespace("g", "http://base.google.com/ns/1.0")).getValue())
- 雖然我不確定您的實際 XML 資料并且我無法對此進行測驗,但我認為對于您的 XML 資料,
Logger.log(items[1].getChild('id', XmlService.getNamespace("http://base.google.com/ns/1.0")).getValue())可能會起作用。
參考:
- 獲取命名空間(uri)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487911.html
標籤:javascript xml 谷歌应用脚本 xml 解析
