问题
您有一些 XML 数据想要导入到 JMP 数据表中。
在此示例中,我使用 JMP 用户社区的 RSS 源获取
此处的加载项。以下是提要的片段。
解决方案
使用解析 XML JSL 函数从 XML 结构中获取文本并将数据插入到 JMP 数据表中。
要使用 Parse XML(),您需要了解三个命名参数:元素上、开始标记和结束标记。
- On Element :定义对特定标记执行的操作(使用开始标记和/或结束标记参数)
- 开始标签:定义一个脚本在开始标签时运行(例如“ ") 已达到。在开始标记脚本中,您可以使用 XML Attr() 函数访问 XML 属性。
- 结束标记:定义到达结束标记(例如“”)时运行的脚本。在结束标记脚本中,您可以使用 XML Text() 函数访问元素的文本(即开始标记和结束标记之间的文本)。
您在 Parse XML 函数中包含的 On Element 参数的顺序并不重要。将这些参数视为定义当您从上到下查看文档时遇到每个元素时应该发生的情况。
当您需要从元素获取 XML Attr() 以及需要设置或创建将在元素子元素(或结束标记)内设置的变量时,应使用开始标记脚本。结束标记脚本应用于获取 XML 元素文本(在开始标记和结束标记之间)。这些开始标记和结束标记脚本都是在 JMP 开始解析实际 XML 字符串之前定义的。这就是为什么您放置它们的顺序并不重要,当解析字符串时找到开始或结束标记时,将引用这些脚本。
当解析 XML 函数到达 XML 字符串中的某个元素时,它会检查是否存在为该元素定义的开始标记脚本,如果存在,则会对其进行求值。它对每个子元素执行此操作,直到到达元素的结束标记。当它到达结束标记时,它会查找该元素的结束标记脚本并对其进行评估(如果存在)。
rssFeed_str = Load Text File( "https://community.jmp.com/kvoqx44227/rss/board?board.id=add-ins" );
// create the data table. could also do this in the
dt = New Table( "RSS Data",
New Column( "ChannelTitle", "Character" ),
New Column( "ChannelPubDate", "Character" ),
New Column( "ChannelLink", "Character" ),
New Column( "ChannelDescription", "Character" ),
New Column( "Title", "Character" ),
New Column( "Link", "Character" ),
New Column( "Description", "Character" ),
New Column( "PubDate", "Character" ),
New Column( "Creator", "Character" )
);
// boolean value to know if we are in an item tag
inItem = 0;
Parse XML( rssFeed_str,
On Element(
"item",
Start Tag(
// turn on the inItem flag
// this is needed to differentiate between
// tags for the channel and ones for and item
inItem = 1;
// ad a row to the data table
dt << Add Rows( 1 );
// add row data to the data table for the channel
dt:ChannelTitle = channel_title;
dt:ChannelPubDate = channel_pubDate;
dt:ChannelLink = channel_link;
dt:ChannelDescription = channel_description;
),
End Tag(
// reset the inItem flag
inItem = 0;
)
),
on element(
"title",
End Tag(
// since the title tag exists for both the channel and each item,
// we want to preserve the channel title separately from the
// current item's title
// This same logic is used for the remaining elements
If( inItem == 0,
channel_title = XML Text(),
dt:Title = XML Text()
)
)
),
on element(
"link",
End Tag(
If( inItem == 0,
channel_link = XML Text(),
dt:Link = XML Text()
)
)
),
on element(
"description",
End Tag(
If( inItem == 0,
channel_description = XML Text(),
dt:Description = XML Text()
)
)
),
on element(
"pubDate",
End Tag(
If( inItem == 0,
channel_pubDate = XML Text(),
dt:PubDate = XML Text()
)
)
),
on element(
"dc:creator",
End Tag( If( inItem == 1, dt:Creator = XML Text() ) )
)
);