I am trying to pull all data by searching for a specific node. My code below can only print out all the nodes but what if I only want to pull information on pantone 101 for example and print out all of the other nodes such as the colors within that specific pantone 101 node. Here is the code I've created to print out the XML data, how can I edit this to only print a specific node. Thanks!
<inventory>
<Product pantone="100" blue="7.4" red="35" green="24"> </Product>
<Product pantone="101" blue="5.4" red="3" rubine="35" purple="24"> </Product>
<Product pantone="102" orange="5.4" purple="35" white="24"> </Product>
<Product pantone="103" orange="5.4" purple="35" white="24"> </Product>
<Product pantone="104" orange="5.4" purple="35" white="24"> </Product>
<Product pantone="105" orange="5.4" purple="35" white="24"> </Product>
<Product pantone="106" black="5.4" rubine="35" white="24" purple="35" orange="5.4"> </Product>
</inventory>
//
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class ReadXML {
public static void main(String args[]) throws Exception {
DocumentBuilderFactory buildFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = buildFactory.newDocumentBuilder();
Document document = dBuilder.parse(ReadXML.class.getResourceAsStream("data.xml"));
document.normalize();
//get main node
NodeList rootNodes = document.getElementsByTagName("inventory");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
//print all with specific tag
NodeList inventoryList = rootElement.getElementsByTagName("Product");
for(int i = 0; i < inventoryList.getLength(); i++){
Node pantone = inventoryList.item(i);
Element pantoneElement = (Element) pantone;
//remove blank elements
System.out.println("Pantone: " + pantoneElement.getAttribute("pantone")); // print attribute
System.out.println("Blue: " + pantoneElement.getAttribute("blue"));
System.out.println("Red: " + pantoneElement.getAttribute("red"));
System.out.println("Orange: " + pantoneElement.getAttribute("orange"));
System.out.println("White: " + pantoneElement.getAttribute("white"));
System.out.println("Purple: " + pantoneElement.getAttribute("purple"));
System.out.println("Green: " + pantoneElement.getAttribute("green"));
System.out.println("Black: " + pantoneElement.getAttribute("black"));
System.out.println("Rubine: " + pantoneElement.getAttribute("rubine"));
}
} catch (ParserConfigurationException | SAXException | IOException e) {
}
}
}