2012-09-13 96 views
0

我有一個XML,它看起來像獲取XML節點的localName

<Personnel> 
    <Employee type="permanent"> 
     <Name>Seagull</Name> 
     <Id>3674</Id> 
     <Age>34</Age> 
    </Employee> 
    <Employee type="contract"> 
     <Name>Robin</Name> 
     <Id>3675</Id> 
     <Age>25</Age> 
    </Employee> 
    <Employee type="permanent"> 
     <Name>Crow</Name> 
     <Id>3676</Id> 
     <Age>28</Age> 
    </Employee> 
</Personnel> 

我試圖讓每一個節點的名稱,然後才能從那裏值,但我一直都想與空或當我做下面的空字符串:

child.getLocalName()等於(「永久」)

它拋出異常,因爲child.getLocalName()爲null 我檢查了孩子在調試器和我看到localName =「permanent」

有沒有人熟悉這種奇怪的行爲?

+0

你們是不是拿每個節點的值? – Ars

回答

0

嘗試可以嘗試使用以下...

DOM Parser 

SAX Parser 

Pull Parser 

JAXP AND JAXB 

Castor 

下面是關於如何使用DOM解析器代碼片段.....

DocumentBuilderFactory odbf = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder odb = odbf.newDocumentBuilder(); 
      InputSource is = new InputSource(new StringReader(xml)); 
      Document odoc = odb.parse(is); 
      odoc.getDocumentElement().normalize(); // normalize text representation 
      System.out.println ("Root element of the doc is " + odoc.getDocumentElement().getNodeName()); 
      NodeList LOP = odoc.getElementsByTagName("locations"); 
      int totalPersons =LOP.getLength(); 
      System.out.println("Total nos of locations:"+totalPersons); 

      for(int s=0; s<LOP.getLength() ; s++) 
      { 
       Node FPN =LOP.item(s); 
       if(FPN.getNodeType() == Node.ELEMENT_NODE) 
        { 

        Element latlon = (Element)FPN;                // Change 1 

        NodeList oNameList1 = latlon.getElementsByTagName("featured");          // Change 2 
        Element firstNameElement = (Element)oNameList1.item(0); 
        NodeList textNList1 = firstNameElement.getChildNodes(); 
        //this.setLocationId(((Node)textNList1.item(0)).getNodeValue().trim()); // Change 3 
        featuredArr = changeToBoolean(((Node)textNList1.item(0)).getNodeValue().trim());         // value taken 
        System.out.println("#####The Parsed data#####"); 
        System.out.println("featured : " + ((Node)textNList1.item(0)).getNodeValue().trim());   // Change 4 
        System.out.println("#####The Parsed data#####");