What am I doing wrong here? I am getting the error there there is nothing in the input stream when that is not the case. The file is there and it is titled correctly. I want to grab the ip addresses i have put in my XML file. Is there a better way to parse in the file instead of dBuilder.parse(XMLReader.class.getResourceAsStream("C:\\Tools\\CLA\\test.xml"));
?
I am experiencing this exception:
Caused by: java.lang.IllegalArgumentException: InputStream cannot be null
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at com.Intel.ameier.XMLparser.TryXML(XMLparser.java:17)
Here is the code:
import java.io.IOException;
import org.xml.sax.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class XMLparser {
protected void TryXML() throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = builderFactory.newDocumentBuilder();
Document document = dBuilder.parse(XMLReader.class.getResourceAsStream("C:\\Tools\\test.xml"));
document.normalize();
NodeList rootNodes = document.getElementsByTagName("info");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element)rootNode;
NodeList compList = rootElement.getElementsByTagName("computer");
for(int i = 0;i < compList.getLength(); i++){
Node computer = compList.item(i);
Element compElement = (Element)computer;
Node theIP = compElement.getElementsByTagName("ipaddress").item(0);
Element theIpElement = (Element)theIP;
System.out.println("The comptuer ip is : " + theIpElement.getTextContent());
}
}
}
XML File:
<?xml version="1.0"?>
<info>
<testsuite>
<name></name>
</testsuite>
<computer>
<ipaddress>111.11.11.6</ipaddress>
</computer>
<computer>
<ipaddress>111.11.11.5</ipaddress>
</computer>
<computer>
<ipaddress>111.11.11.3</ipaddress>
</computer>
</info>
This has nothing to do with XML. You're using Class.getResourceAsStream
, which is meant to get a resource to be loaded from the classpath for that class's class loader... but you're passing in a filename instead.
If you want to create an input stream for a file, just use FileInputStream
:
Document document = dBuilder.parse(new FileInputStream("C:\\Tools\\test.xml"));
Or better, in order to close the stream:
Document document:
try (InputStream stream = new FileInputStream("C:\\Tools\\test.xml")) {
document = dBuilder.parse(stream);
}
See more on this question at Stackoverflow