Reputation: 35
I have an XML file that I am trying to search using Java. I need to find an element by its attribut value (Port number) and return the depending description of the element.
The xml file of known ports should be hosted online and has an architecture like:
<ports>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
<record>
<number></number>
<name></name>
<protocol></protocol>
<description></description>
</record>
</ports>
The elements have no unique identifier. In my application i want to call a function with a number as parameter and it shoult give me the description of the item with the given attribute "number".
My problem is, its a list of all known ports and i cannot manually edit the structure to assign all elements with the portnumber as attribute. can anyone show me how to solve that?
thanks in advance
UPDATE: i want to search it like get_port(int portno)
. thats my code:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOMExampleJava {
public static void main(String args[]) {
try {
File input = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(input);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("record");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Port number: " + getValue("number", element));
System.out.println("Protocol: " + getValue("protocol", element));
System.out.println("Description: " + getValue("description", element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
Upvotes: 0
Views: 2328
Reputation: 527
Create your own HashMap obj inside the method and you can get the record you want from the list. E.g. HashMap<int itemId, List<item>> yourOwnItem = new HashMap<>();
At the end of the for loop pass the item to yourOwItem as follows:
yourOwnItem.put(i , List<item>);
Upvotes: 1