mzjnで提案されているように、私は全体の質問を変更して単純化しようとしています。Python lxml libraryには、空のタグにNoneが含まれています
私はこのXMLを持っている:
<Content Version="1.0" Name="Cont">
<Element Ref="Text_4158" ElementType="ItISSomething" GroupName="Some_Content">
<body>
<p>Some content is here.</p>
</body>
</Element>
<Element Ref="List_585" ElementType="ListElements" GroupName="Lists">
<body>
<p><span class="bold">A list of things</span>: Element1, element2, element3, element4 element5.</p>
</body>
</Element>
</Content>
私は "" リストの内容を変更し、交換したい "<、>"。そして、私はこのコードを持っている:
from lxml import etree as et
def replace_commas(file):
parser = et.parse(str(file))
root = parser.getroot()
xpath_expr = "//Element[starts-with(@Ref,'List_') \
or @GroupName='Lists']/descendant::*"
elements = root.xpath(xpath_expr)
for element in elements:
if element.text is not None or element.tail is not None:
text = str(element.text)
text = text.replace(',', '<,>')
tail = str(element.tail)
tail = tail.replace(',','<,>')
element.text = text
element.tail = tail
tree = et.ElementTree(root)
tree.write(file, pretty_print=True)
予想される出力は次のようになります。
<Content Version="1.0" Name="Cont">
<Element Ref="Text_4158" ElementType="ItISSomething" GroupName="Some_Content">
<body>
<p>Some content is here.</p>
</body>
</Element>
<Element Ref="List_585" ElementType="ListElements" GroupName="Lists">
<body>
<p><span class="bold">A list of things</span>: Element1<,> element2<,> element3<,> element4 element5.</p>
</body>
</Element>
</Content>
私の結果はしかし:
<Content Version="1.0" Name="Cont">
<Element Ref="Text_4158" ElementType="ItISSomething" GroupName="Some_Content">
<body>
<p>Some content is here.</p>
</body>
</Element>
<Element Ref="List_585" ElementType="ListElements" GroupName="Lists">
<body>
<p>None<span class="bold">A list of things</span>: Element1<,> element2<,> element3<,> element4 element5.</p>
</body>
</Element>
</Content>
タグ "P" と「スパンの間にどれを取得しません"何もないはずです。なにが問題ですか?
質問に対するこのアップデートがクエリを理解し、解決策を見つけるのに役立ちます。
更新: def replace_commas(file):のコロンを修正し、et.ElementTree(root)の字下げを修正しました。
また、mzjnで提案されている解決策でエラーが発生している箇所が見つかりました。それは価値なしとなるよう、私は重要な要素の尾部にNoneTypeを取得し、この素子では
<Element Ref="List_222"ElementType="ListElements" GroupName="Lists">
<body>
<p><span class="bold">List: <span class="italic">Important elements</span></span>: El1 (prop1), el2 (prop2), el3 (prop3); with a special property.</p>
</body>
</Element>
:私は私のXMLでこの要素を持っています。
私はそれを解決する方法を見ていません。
あなたは望ましいケースを追加できますか? – Jonathan
私は望ましい事例を追加しました。それはNone値なしの空要素になります。私は原因についての私の小さな研究についていくつかの情報を追加しました。しかし、私は何も見つかりませんでした。 – TMikonos
質問を簡略化して[mcve]を作成してください。 – mzjn