2016-06-13 63 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