Google News Sitemap をPythonの標準xmlライブラリであるElementTreeを使って作成しています。
しかし、作成済みのxmlファイルを読み込んで、URLを追加したあとに、namespaceを付けて出力しようとすると期待した結果を得ることができません。
以下にコードを記載します。
main.py
#!python3.7
# -*- coding: utf-8 -*-
# news-ranking.py
from datetime import datetime, timedelta
import xml.etree.ElementTree as ElementTree
import os
from pprint import pprint
class NewsSitemapXMLGenerator:
def __init__(self):
self.xml = ElementTree.parse('/xml/path/news-sitemap.xml').getroot()
def generate(self):
self.addElement()
ElementTree.register_namespace('', 'http://www.sitemaps.org/schemas/sitemap/0.9')
ElementTree.register_namespace('news', 'http://www.google.com/schemas/sitemap-news/0.9')
string = ElementTree.tostring(self.xml, 'unicode')
with open('/xml/path/news-sitemap.xml', mode='w') as fo:
fo.write("<?xml version='1.0' encoding='UTF-8'?>" + string)
def addElement(self):
url = ElementTree.SubElement(self.xml, 'url')
ElementTree.SubElement(url, 'loc').text = 'loc'
news = ElementTree.SubElement(url, 'news:news')
publication = ElementTree.SubElement(news, 'news:publication')
ElementTree.SubElement(publication, 'news:name').text = 'name'
ElementTree.SubElement(publication, 'news:language').text = 'jp'
ElementTree.SubElement(news, 'news:publication_date').text = 'date'
ElementTree.SubElement(news, 'news:title').text = 'title'
return self.xml
def main():
generator = NewsSitemapXMLGenerator()
generator.generate()
if __name__ == '__main__':
main()
news-sitemap.xml(実行前)
<?xml version='1.0' encoding='UTF-8'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" />
news-sitemap.xml(実行後)
<?xml version='1.0' encoding='UTF-8'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />
xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" を宣言したままにしたいのですが、実行後には削除されてしまいます。
解決方法をご存じの方、よろしくお願いします。
12/16追記
xmlの記述が既にあり、これに要素を追加するパターンにも対応したいと思っています。
よろしくお願いします。
news-sitemap2.xml
<?xml version='1.0' encoding='UTF-8'?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
<url>
<loc>loc</loc>
<news:news>
<news:publication>
<news:name>name</news:name>
<news:language>jp</news:language>
</news:publication>
<news:publication_date>date</news:publication_date>
<news:title>title</news:title>
</news:news>
</url>
</urlset>
:
)を含む namespace 名を指定できませんので、その点が面倒かも知れません。