我正在尝试将我的XML文件中的打印机(printerName)的特定IP地址读入我的java程序。这是XML的开头,我想抓住一个打印机名称......
<?xml version="1.0" encoding="UTF-8"?>
<Platform>
############################
#Printer Specific ##########
############################
<THISPrinter name="Printer" printerName="172.27.17.200" version="v2.1.113" />
因为我只需要printerName,所以我认为我不需要创建一个for循环来创建像我在这个完全不相关的例子中找到的节点和元素......
NodeList nList = doc.getElementsByTagName("employee");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
//Create new Employee Object
employee = new Employee();
employee.setId(Integer.parseInt(eElement.getAttribute("id")));
employee.setFirstName(eElement.getElementsByTagName("firstName").item(0).getTextContent());
employee.setLastName(eElement.getElementsByTagName("lastName").item(0).getTextContent());
employee.setLocation(eElement.getElementsByTagName("location").item(0).getTextContent());
//Add Employee to list
employees.add(employee);
}
}
以下是我尝试获取printerName ...但该程序没有对它执行任何操作,之后又出现问题。任何建议都会很棒!
String printerName = doc.getElementsByTagName("SaberK3Printer").item(1).getTextContent();
System.out.println(printerName);
答案 0 :(得分:0)
我想通了,我需要让Node打印机然后指定什么attr和我这是printerName!然后我在我的JTextField中设置IP地址......
public void setIPAddress() throws IOException, ParserConfigurationException, SAXException{
try{
//hardcoded file path to where printer ip is located
File fXmlFile = new File("/Users/SRC/PerfTest/BaseTest/XML/SaberPlatform.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize(); //suggested to do
System.out.println("Root element : " + doc.getDocumentElement().getNodeName());//should be Platform during execution
Node printer = doc.getElementsByTagName("SaberK3Printer").item(0);
NamedNodeMap attr = printer.getAttributes();
Node nodeAttr = attr.getNamedItem("printerName");
System.out.println(nodeAttr);
int firstQuote = nodeAttr.toString().indexOf("\"");
String shortenedIP = nodeAttr.toString().substring(firstQuote + 1, nodeAttr.toString().length() - 1);
ipText.setText(shortenedIP);
}
catch (IOException e){
System.out.println("ip .xml file not found");
}
catch(ParserConfigurationException d){
System.out.println("ParserConfigurationException thrown in setIPAddress");
}
catch(SAXException f){
System.out.println("SAXException thrown in setIPAddress");
}
}//end of setIPAddress