Reputation: 7845
Here's my code:
'''
Created on 27/05/2015
@author: Rederick Deathwill
'''
from java.io import File
from java.io import IOException
from javax.xml.parsers import DocumentBuilder
from javax.xml.parsers import DocumentBuilderFactory
from org.w3c.dom import Document
from org.w3c.dom import Element
from org.w3c.dom import Node
from org.w3c.dom import NodeList
from org.xml.sax import SAXException
class JXLLoader():
def __init__(self, fileName):
self.fileName = fileName
self.file = File(self.fileName)
self.dbFactory = DocumentBuilderFactory.newInstance()
self.dBuilder = self.dbFactory.newDocumentBuilder()
self.doc = self.dBuilder.parse(self.file)
self.doc.getDocumentElement().normalize()
class JXLReader(JXLLoader):
def __init__(self, fileName):
JXLLoader.__init__(self, fileName)
self.mainNodeList = self.doc.getElementsByTagName("main") # Here <<
if __name__ == '__main__':
jxl = JXLReader("x.xml")
print(jxl.mainNodeList)
for i in range(jxl.mainNodeList.getLength()):
node = jxl.mainNodeList.item(i)
if (node.getNodeType() == Node.ELEMENT_NODE):
e = node
print(e.getElementsByTagName("value").item(0).getTextContent())
Is there a way to check if the "TagName" exists within the Document object? I don't know how to check if the tag "main" is not present. For example:
The result of that print(jxl.mainNodeList) is:
com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl@58a63629
Nevertheless, if I do this with a tag that does not exist:
self.mainNodeList = self.doc.getElementsByTagName("maix")
The result when I print is an address/object just like that one (Instead of a null / None or something). The point is, how am I going to know if "< main >< / main >" is really in the Document so that I can raise an Exception in case it isn't?
Here's the XML:
<?xml version="1.0" encoding="UTF-8"?>
<main>
<value>100</value>
<name>Rederick Deathwill</name>
</main>
EDIT: Also, I've checked the docs. There's not method like "hasTagName()".
Upvotes: 1
Views: 2370
Reputation: 74655
Check the length of the return value of the getElementsByTagName
call.
If self.mainNodeList.getLength() == 0
then the getElementsByTagName
call found nothing.
Upvotes: 2