目标:使用xmlstarlet提取子HTML元素的值,并重复使用不同的值并将其导出为CSV
数据:
<?xml version="1.0" encoding="UTF-8"?>
<Library export_date="2020-01-15">
<Book id="1001">
<Title>Book 1</Title>
<Date value="2019-05-16"/>
<Author value="Name 1"/>
<Author value="Name 2"/>
<Author value="Name 3"/>
<Author value="Name 4"/>
<Author value="Name 5"/>
<Author value="Name 6"/>
<Author value="Name 7"/>
<Author value="Name 8"/>
<Author value="Name 9"/>
<Author value="Name 10"/>
<Author value="Name 11"/>
<Author value="Name 12"/>
<Author value="Name 13"/>
</Book>
</Library>
尝试:
xmlstarlet \
sel -T -t -m /Library/Book \
-v "concat('"','Title','","',Author/@value,'"')" \
-n library_books.xml \
> output.csv
# Remove xmlstarlet quotation bypass, convert to actual quotation
sed -i .bak 's|"|\"|g' output.csv
CSV输出:
"Title","Name 1"
所需的CSV输出:
"Title","Name 1; Name 2; Name 3; Name 4; Name 5; Name 6; Name 7; Name 8; Name 9; Name 10; Name 11; Name 12; Name 13"
所需的CSV替代输出(新行中的值):
"Title","Name 1
Name 2
Name 3
Name 4
Name 5
Name 6
Name 7
Name 8
Name 9
Name 10
Name 11
Name 12
Name 13"