How do I pull from within a nested tag with javascript?
Obviously, I'm new to Javascript, and I'm sure that my time with it will be shortlived; this is just for a small project at work. I would really appreciate it if someone would help me figure this out.
I'm trying to set up a page that displays data from an external .xml file, of which I have absolutely no control. It is set up just like this:
<lab id="1" name="A" inUse="14" offline="1" available="16">
</lab>
<lab id="2" name="B" inUse="11" offline="9" available="7">
<client id="x" status="available" mac="#" ip="#" name="COMPUTER1" />
<client id="y" status="available" mac="#" ip="#" name="COMPUTER2" />
</lab>
I am displaying the data with a table using the following code:
<%
try
{
URL url = new URL("http://clstats.cc.nd.edu/public/xml-client.jsp");
InputStream input = url.openStream();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLInfo = builder.parse(input);
NodeList labs = XMLInfo.getElementsByTagName("lab");
int length = labs.getLength();
int i;
for (i = 0; i < length; i++)
{
Node current = labs.item(i);
String labName = current.getAttributes().getNamedItem("name").getTextContent();
String available = current.getAttributes().getNamedItem("available").getTextContent();
String offline = current.getAttributes().getNamedItem("offline").getTextContent();
String inUse = current.getAttributes().getNamedItem("inUse").getTextContent();
//Alternate the row colors
if( (i % 2) == 0)
{
%>
<tr style="background:url(#);">
<%
}
else
{
%>
<tr style="background:url(#);">
<%
}
%>
<td><%= labName %></td>
<td><%= available %></td>
开发者_如何学Python <td><%= offline %></td>
<td><%= inUse %></td>
</tr>
</td>
<%
}
}
catch(Exception e){
}
%>
I am having no trouble displaying information from the "lab" tag, but I'd like to only display data from within a particular lab, let's say lab id=2. Is there a way to display attributes from the "client" tags from under a single, particular "lab" tag?
Thanks, I hope I explained the problem well enough. As you can see, I'm pretty much a noob, and any help would be much appreciated.
Intended Result:
<table>
<tr>
<td>Name</td>
<td>Status</td>
</tr>
<tr>
<td>COMPUTER1</td>
<td>Available</td>
</tr>
<tr>
<td>COMPUTER2</td>
<td>AVAILABLE</td>
</tr>
</table>
You are using getElementsByTagName
on the XMLInfo to get labs. I think you can also use Nodelist clients = current.getElementsByTagName("client");
then iterate through those nodes.
That looks like java to me in which case I think you could use Xpath like this:
InputStream input = url.openStream();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLInfo = builder.parse(input);
XPath xPath = XPathFactory.newInstance().newXPath();
Node myNode = xPath.evaluate("/lab[@id='2']", XMLInfo, XPathConstants.NODESET);
That should get you the individual node.
精彩评论