开发者

Preserve XML Tags - Python DOM Implementation

I have just finished skiming through the python DOM API and can't seem to find what I am looking for.

I basically want to preserve the XML tags when traversing through the DOM tree. The idea is to print the tag name and corresponding attributes which I later want to convert into an xml file.

<book name="bookname" source="/home/phiri/Book/book.xml"
      xmlns:xi="http://www.w3.org/2001/XInclude">
  <chapter>
    <page>page1</page>
    <page>page2</page>
  </chapter>
  <chapter>
    <开发者_StackOverflowpage>page1</page>
    <page>page2</page>
    <page>Page3</page>
  </chapter>
</book>

Using the XML contents above for instance, what I want is for the result of the book.xml file to have.

<book name="bookname" source="/home/phiri/Book/book.xml"
      xmlns:xi="http://www.w3.org/2001/XInclude">
  <chapter></chapter>
  <chapter></chapter>
</book>

Is there an alternative xml package I could use to preserve results I get when extracting contents using python?


A simple way to get the output you posted from the input is to override the XSLT identity transform. It looks like you want to eliminate all text nodes and all elements that have more than two ancestors, so you'd just add empty templates for those:

<xsl:template match="text()"/>

<xsl:template match="*[count(ancestor::*) &gt; 2]"/>

Generally the best way to use XSLT in Python is with the libxml2 module. Unless you need a pure Python solution, in which case you're stuck not using XSLT, because nobody's built a pure Python XSLT processor yet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜