2016-06-13 73 views
0

我正在嘗試將我的XML文件中的打印機(printerName)的特定IP地址讀入到我的java程序中。下面是與一個PRINTERNAME我要搶XML的開始......在java程序中讀取xml

<?xml version="1.0" encoding="UTF-8"?> 
<Platform> 
    ############################ 
    #Printer SpecifiC########## 
    ############################ 

    <THISPrinter name="Printer" printerName="172.27.17.200" version="v2.1.113" /> 

因爲我只需要我想我並不需要做一個for循環,使節點和元素,如我的PRINTERNAME 「已經在此完全無關的例子中發現...

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

您知道#中的註釋是無效的XML,對吧?這是你想要解析的確切流嗎? – duffymo

+0

「SaberK3Printer」所在XML的一瞥也將有所幫助。我沒有看到它在你的XML例子中的任何地方。 –

回答

0

我想通了,我需要得到節點打印機,然後指定什麼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