Re: CDATA extraction
Dethe Elza <[email protected]> Wed, 17 Dec 2003 11:22:06 -0800
| Newsgroups | gmane.comp.web.zope.parsed-xml |
|---|---|
| Message-ID | <[email protected]> |
On 17-Dec-03, at 9:01 AM, [email protected] wrote: > <?xml version="1.0" encoding="UTF-8"?> > <!-- A problem to get value in CDATA block --> > <problem> > <title>My problem</title> > <content>How can I get the string shown in the CDATA marked > sections?</content> > <![CDATA[ "Please help me." ]]> > </problem> OK, first off, there are several ways of going about this, especially XPath, walking the DOM tree, or event-driven. Here is an example of walking the DOM tree, but keep in mind that there may be better ways depending on what you're trying to accomplish. This code assumes that your example is saved as a file "test.xml" in the current directory. =========== snip ============ from xml.dom.ext.reader import PyExpat from xml.dom import Node data = file('test.xml') reader = PyExpat.Reader() document = reader.fromStream(data) data.close() def walkToCDATA(node): if node.nodeType == Node.CDATA_SECTION_NODE: print node.nodeValue for child in node.childNodes: walkToCDATA(child) walkToCDATA(document) =========== snip ============ I hope that helps. --Dethe "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. " --Brian Kernighan