2013-09-02 2 views
1

Dom 파서를 사용하여 아래 XML을 구문 분석합니다.XML 구문 분석에서 null을 반환합니다.

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<company> 
    <Staff id="1"> 
     <firstname>Achyut</firstname> 
     <lastname>khanna</lastname> 
     <nickname>Achyut</nickname> 
     <salary>900000</salary> 
    </Staff> 
</company> 

XML에서 firstName 만 필요한 이유는 null입니까?

private String getNodeValue(Node node) { 
     Node nd = node.getFirstChild();  
     try { 
      if (nd == null) { 
       return node.getNodeValue();    
      } 
      else {    
       getNodeValue(nd); 
      } 
     } catch (Exception e) { 

      e.printStackTrace(); 
     } 
     return null; 
    } 
+1

디버거는 무엇을 말하는가? – fiscblog

+0

Staff 노드를 노드 매개 변수로 전달합니까? – AurA

+0

어떤 XML 라이브러리를 사용하고 있습니까? 어떤 종류의 객체 (어떤 패키지와 클래스)가'Node' 인자입니까? – Stewart

답변

0

우선 DOM 통과를 사용하여 XML을 구문 분석하지 않는 것이 좋습니다. OXM (JaxB 또는 XMLbeans)을 사용하는 것이 좋습니다. 그러나 당신이이 방법에 관심 아직도 경우 : 여기

하면 코드를입니다

public class T2 { 
public static void main(String []args) throws ParserConfigurationException, SAXException, IOException{ 
DocumentBuilder db = null; 

String xmlString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><company> <Staff id='1'>  <firstname>Achyut</firstname>  <lastname>khanna</lastname>  <nickname>Achyut</nickname>  <salary>900000</salary> </Staff></company>"; 
Document doc = null; 
InputSource is = new InputSource(); 

is.setCharacterStream(new StringReader(xmlString)); 

    db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
    doc = db.parse(is); 

    NodeList nodes = doc.getElementsByTagName("firstname"); 

    for (int i = 0; i < nodes.getLength(); i++) { 
     if (nodes.item(i) instanceof Element) { 
      Node node = (Node) nodes.item(i); 
      nodes.item(i); 

      String fName = getCharacterDataFromElement(node); 
      System.out.println(fName); 
     } 
    } 


} 
private static String getCharacterDataFromElement(Node e) { 
    Node child = e.getFirstChild(); 
    if (child instanceof CharacterData) { 
     CharacterData cd = (CharacterData) child; 
     return cd.getData(); 
    } 
    return null; 
} 
} 

당신은 노드 목록을 가져 오기 다음 매개 변수로 해당 노드 값을 통과해야 Achyut

1

인쇄 위의 코드 정의 된 함수를 호출 할 때.

NodeList n = item.getElementsByTagName("Staff"); 

그리고 대신 XPath를 사용하여 자신을 저장 기능 코드를 많이

String firstName = getNodeValue(n.item(0)); 
+0

하지만 디버거를 사용하면 줄을 반환하고 Achyut에 값을 표시하지만 다른 내부에 다시 ​​들어가는 이유가 있습니다. 왜요? – Achyut

+0

작성한 코드는 전달 된 Node 값이있는 경우 첫 번째 자식을 반환하는 함수입니다. 여기서 유일한 문제는 잘못된 노드 값을 사용하여 호출하는 것일 수 있습니다. – AurA

0

전화 :

XPath xp = XPathFactory.newInstance().newXPath(); 
InputSource in = new InputSource(...); 
String fn = xp.evaluate("/company/Staff[@id='1']/firstname/text()", in); 
System.out.println(fn); 

printts :

Achyut 
관련 문제