如何迭代 XML 文件,将属性对作为输出 CSV 文件中的行提取

How to iterate over XML file, pulling out attribute pairs as rows in an output CSV file

我找不到符合这个特定要求组合的答案,我被卡住了。

我的文件是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<lvl1>
  <lvl2>
    <lvl3>
      <topic label="grandparent" href="gp1.html">
        <topic label="parent" href="p1.html">
           <topic label="child" href="c1.html">
              <topic label="grandchild1" href="gc1.html"/>
              <topic label="grandchild2" href="gc2.html"/>
...

我想要的输出是这样的:

gradparent,gp1.html
parent,p1.html
child,c1.html
grandchild1,gc1.html
grandchild2,gc2.html

即目标是将成对的标签和 href 展平到一个 csv 文件中。我的源文件有多个嵌套的主题元素,这些元素有很多层次,其中一些具有同级主题元素。

我试过类似的东西:

let $input := (my_file.xml)
let $nl := "&#10;"
let $output :=
string-join(
for $topic in $input//topic 
return
string-join(
for $lab in $topic/*
return
$lab/@label/data()
, ',')
, $nl)

return $output

但这甚至还没有做到一半...很想知道我还差多远。谢谢

您可以使用 @* 获取所有属性,但顺序未指定。所以使用(@label,@href)。不需要一秒钟 for:

let $input := (my_file.xml)
let $nl := "&#10;"
let $output :=
  string-join(
    for $topic in $input//topic 
    return string-join($topic/(@label,@href), ',')
  , $nl)
return $output

你甚至不需要第一个for:

let $input := (my_file.xml)
let $nl := "&#10;"
let $output :=
  string-join(
    $input//topic/string-join((@label,@href), ',')
  , $nl)
return $output