質問するログイン新規登録

回答編集履歴

1

XMLのパースについて追記

2020/06/17 15:15

投稿

teamikl
teamikl

スコア8824

answer CHANGED
@@ -8,4 +8,27 @@
8
8
  ```python
9
9
  s = e(title).encode('utf-8', 'xmlcharrefreplace')
10
10
  outfp.write('<outline level="{!r}" title="{}">\n'.format(level, s))
11
+ ```
12
+
13
+ ----
14
+ 追記: XMLのパースについて、`<outline>` の `title` 要素のリストアップは
15
+ 以下のように変換できます。出力結果を sample.xml として、
16
+
17
+ ```
18
+ import sys
19
+ import ast
20
+ import xml.etree.ElementTree as ET
21
+
22
+ # title が "b'....'" の様に多重にクォートされているのを解消する。
23
+ FIX_3K_BYTES = True
24
+
25
+ def main(filepath="sample.xml"):
26
+ fix = ast.literal_eval if FIX_3K_BYTES else (lambda _:_)
27
+ doc = ET.parse(filepath).getroot()
28
+ for outline in doc.findall(r"outline"):
29
+ title = fix(outline.attrib["title"]).decode("utf-8")
30
+ print(title)
31
+
32
+ if __name__ == '__main__':
33
+ main(*sys.argv[1:])
11
34
  ```