尝试访问第一项的子项时出现空结果。我正在使用 Google 应用脚本。
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>
最佳答案
我相信您当前的问题和目标如下。
-
Logger.log(items[1].getChild('g:id'))
返回null
. - 您想要从
<g:id>###</g:id>
检索值在item
通过修改您的脚本。
当我看到您显示的 XML 和您的脚本时,在您的脚本中,我认为需要使用 namespace 。当这反射(reflect)在您的脚本中时,它会变成如下所示。
来自:
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())
可能会起作用。
引用:
关于javascript - 获取子节点时 XML Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72541853/