Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XML Parsing.. 2

Status
Not open for further replies.

Tokhra

Programmer
Oct 1, 2003
134
ES
Hi All,

Im attempting to write a xml based authentication java bean, the xml files is structured as follows:

<users>

<user>
<username>Admin</username>
<password>Test</password>

<firstname>Bob</firstname>
</user>

<user>
<username>User</username>
<password>Test</password>

<firstname>Jim</firstname>
</user>

</user>

Theres more information for each user, but you get the idea.

I've got the following code, I think it'll loop through the <user></user> elements ? but then im unsure howto delve deeper into the element and get at its sub elements?

Also i've found that I need to use org.w3c.dom.Text to get at the text of a element, any examples of this?

Thanks,

Heres the code I currently have:

// Create URL instance to path
URL url = new URL(path);

// Create JAXP document builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Create JAXP document builder
DocumentBuilder parser = factory.newDocumentBuilder();

// Retrieve stream from xml file
InputStream stream = url.openStream();

// Parse xml data
Document xml = parser.parse(stream);

// Generate node list from xml document
NodeList nodes = xml.getElementsByTagName("User");

// Loop through user nodes
for (int i = 0; i < nodes.getLength(); i++)
{
// Reference current element
Element element = (Element)nodes.item(i);


}

This is using the org.w3c.dom document object models and javax.parsers document builder.

Any help/advice would be greatly appreciated, Thanks,
Matt.
 
Great, exactly what I need - thanks.
 
OK, so i've got this code, what im trying to do is loop all instances of <user> elements, then then loop the child elements of the current <user> element in order to retrieve the username and password elements. Theres 12 elements within the <user> element, but nodeList.getLength() is returning 22!. It doesn't seem to be working at all.

Any ideas what im doing wrong?

Thanks,
Matt.





// Create URL instance to path
URL url = new URL(path);

// Create JAXP document builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Create JAXP document builder
DocumentBuilder parser = factory.newDocumentBuilder();

// Retrieve stream from xml file
InputStream stream = url.openStream();

// Parse xml data
Document xml = parser.parse(stream);

// Generate node list from xml document
NodeList nodes = xml.getElementsByTagName("user");

// Loop through user nodes
for (int i = 0; i <= nodes.getLength()-1; i++)
{
// Reference current node
Node userNode = nodes.item(i);

// Retrieve node list for user node
NodeList userNodes = userNode.getChildNodes();

// Loop through child nodes

for (int j = 0; j <= userNodes.getLength()-1; j++)
{
// Retrieve child node reference
Node currentNode = userNodes.item(j);

if (currentNode.getNodeName().equals("username"))
{
actualUsername = currentNode.getNodeValue();
}
else if (currentNode.getNodeName().equals("password"))
{
actualPassword = currentNode.getNodeValue();
}
}
}
 
Don't worry I had a further look through that link you gave me and found a better solution, Thanks very much again :)
 
@Tokhra
Hi,
I have got the same problem. Can you send me your solution?

thx

Catweathel
 
Hi Catweathel,

This is the XMLParserBean:
-------------------------------------------------------

import java.*;
import java.io.*;
import java.net.*;
import javax.xml.parsers.*;

import org.w3c.dom.*;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;

/**
* Provides methods to facilitate with parsing XML documents.
* @version 1.0.0 22/03/2004
*
**/
public class XMLParserBean
{
/**
* Create new XML Parser class instance.
**/
public XMLParserBean()
{
// Do Nothing.
}

/**
* Open XML document at specified URL using JAXP
* (Java API for XML Parsing).
*
* @param URL Location of XML Document to open.
* @return Document object representing XML DOM.
**/
public Document GetXMLDocument(URL url) throws Exception
{
try
{
// Create JAXP document builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

// Create JAXP document builder
DocumentBuilder parser = factory.newDocumentBuilder();

// Retrieve stream from xml file
InputStream stream = url.openStream();

// Parse xml data and return document intance
return (Document)parser.parse(stream);
}
catch(Exception e)
{
throw e;
}
}

/**
* Get the named subnode in a nodes sublist.
* This method:
* <ul>
* <li>Ignores comments and processing instructions.
* <li>Ignores text nodes.
* <li>Ignores CDATA & EntityRef nodes.
* <li>Examines entity nodes to find one with the specified name.
* </ul>
*
* @param name The Name of Sub Node to retrieve.
* @param node The Node to search for sub node in.
*
* @return The found node.
**/
public Node getSubNode(String name, Node node)
{
// If the node isnt a element node, we cant get a sub node
if (node.getNodeType() != Node.ELEMENT_NODE)
{
return null;
}

// If the node doesn't have childs we cant get sub nodes
if (!node.hasChildNodes())
{
return null;
}

// Retrieve list of sub nodes
NodeList subNodes = node.getChildNodes();

// Loop sub nodes
for (int i = 0; i < subNodes.getLength(); i++)
{
// Reference current node
Node subNode = subNodes.item(i);

// If node is an element
if (subNode.getNodeType() == Node.ELEMENT_NODE)
{
// If the node name matches, return it
if (subNode.getNodeName() == name)
{
return subNode;
}
}
}

return null;
}

/**
* Return the text that a node contains.
* This method:
* <ul>
* <li>Ignores comments and processing instructions.
* <li>Concatenates text nodes, cdata nodes and the results of
* recursively processing entityref nodes.
* <li>Ignores any element nodes in the sublist.
* </ul>
*
* @param node A DOM Node.
* @return String representing node value.
**/
public String getNodeValue(Node node)
{
// Stringbuilder to store data
StringBuffer result = new StringBuffer();

// If the node has no child nodes, theres no value
if (!node.hasChildNodes())
{
return "";
}

// Retrieve list of sub nodes
NodeList subNodes = node.getChildNodes();

// Loop sub nodes
for (int i = 0; i < subNodes.getLength(); i++)
{
// Reference current sub node
Node subNode = subNodes.item(i);

switch(subNode.getNodeType())
{
case Node.TEXT_NODE:
// Append data
result.append(subNode.getNodeValue());
break;

case Node.CDATA_SECTION_NODE:
// Append data
result.append(subNode.getNodeValue());
break;

case Node.ENTITY_REFERENCE_NODE:
// Recurse into subtree for text and Append data
result.append(getNodeValue(subNode));
break;
}
}

return result.toString();
}
}

So you use that to get the xml document, then retrieve the list of <user> nodes, and locate the <username> node within that, if that matches, locate the <password> node, if thats a match the user is authenticated.

My code within an "AuthenticationBean" is below (I also wrote a "AuthenticationTicketBean" too just to store user details through sessions.

Hope this helps :)

---------------------------------------------------

// Create URL instance to path
URL url = new URL(path);

// Create new XML Parser
XMLParserBean parser = new XMLParserBean();

// Retrieve xml document DOM
Document xml = parser.GetXMLDocument(url);

// Get list of nodes for user node
NodeList nodes = xml.getElementsByTagName("user");

for (int i = 0; i < nodes.getLength(); i++)
{
// Reference current node
Node userNode = nodes.item(i);

// Retrieve username node
Node usernameNode = parser.getSubNode("username", userNode);

// If the username is the same as user attempting to login
if (parser.getNodeValue(usernameNode).equalsIgnoreCase(username))
{
// Retrieve password node
Node passwordNode = parser.getSubNode("password", userNode);

// Set variables
actualUsername = parser.getNodeValue(usernameNode);
actualPassword = parser.getNodeValue(passwordNode);

// If the user has supplied correct password for this account
if (actualPassword.equalsIgnoreCase(password))
{
// Setup ticket properties
ticket.setIsAuthenticated(true);
ticket.setUsername(username);
ticket.setPassword(password);
}

break;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top