回答編集履歴

1

XMLのパースについて追記

2020/06/17 15:15

投稿

teamikl
teamikl

スコア8664

test CHANGED
@@ -19,3 +19,49 @@
19
19
  outfp.write('<outline level="{!r}" title="{}">\n'.format(level, s))
20
20
 
21
21
  ```
22
+
23
+
24
+
25
+ ----
26
+
27
+ 追記: XMLのパースについて、`<outline>` の `title` 要素のリストアップは
28
+
29
+ 以下のように変換できます。出力結果を sample.xml として、
30
+
31
+
32
+
33
+ ```
34
+
35
+ import sys
36
+
37
+ import ast
38
+
39
+ import xml.etree.ElementTree as ET
40
+
41
+
42
+
43
+ # title が "b'....'" の様に多重にクォートされているのを解消する。
44
+
45
+ FIX_3K_BYTES = True
46
+
47
+
48
+
49
+ def main(filepath="sample.xml"):
50
+
51
+ fix = ast.literal_eval if FIX_3K_BYTES else (lambda _:_)
52
+
53
+ doc = ET.parse(filepath).getroot()
54
+
55
+ for outline in doc.findall(r"outline"):
56
+
57
+ title = fix(outline.attrib["title"]).decode("utf-8")
58
+
59
+ print(title)
60
+
61
+
62
+
63
+ if __name__ == '__main__':
64
+
65
+ main(*sys.argv[1:])
66
+
67
+ ```