2012-09-13 95 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#####");