2017-06-05 202 views
0

访问孩子的父节点的孩子有一个挑战。如何访问父节点的孩子的孩子节点

String response = "<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<closure> 
    <amount>1055296.0000</amount> 
    <currency>USD</currency> 
    <unit>2</unit>   
    <year>2012</year> 
    <taxes> 
     <tax> 
      <descript>FEE LEVY</descript>    
      <taxAmt> 
       <amt>30304.0000</amt> 
       <currency>USD</currency>      
      </taxAmt> 
      <taxCode>SUR</taxCode> 
     </tax> 
     <tax> 
      <descript>MED LEVY</descript>    
      <taxAmt> 
       <amt>25125.0000</amt> 
       <currency>USD</currency>      
      </taxAmt> 
      <taxCode>CIS</taxCode> 
     </tax>   
    </taxes> 
</closure>";  

下面是代码我曾尝试::下面是XML我与工作

 DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
    InputSource src = new InputSource();` 
    src.setCharacterStream(new StringReader(response)); 
    Document doc = builder.parse(src); 
    String amount =doc.getElementsByTagName("amount").item(0).getTextContent(); 
    NodeList nodeList = doc.getElementsByTagName("tax"); 
    for (int i = 0; i < nodeList.getLength(); i++) 
    { 
    Node childNode = nodeList.item(i); 
    } 

请我如何得到DESCRIPT,taxAmt和taxCode元素税里面?

+0

请缩进您的XML。 – Kaushal28

+0

@ Kaushal28 ...我已经缩进了我的xml。 – hyzic23

回答

0
doc.getElementsByTagName("amount").item(0).getFirstChild().getNodeValue() 
+0

感谢您的回复,我其实想要得到,。请协助 – hyzic23

0

这是我如何能够解决isssue我有: DocumentBuilder的建设者= DocumentBuilderFactory.newInstance()newDocumentBuilder(); InputSource src = new InputSource(); src.setCharacterStream(new StringReader(response)); Document doc = builder.parse(src);

NodeList nodeList = doc.getElementsByTagName("tax"); 
Node node; 

    for (int i = 0; i < nodeList.getLength(); i++) 
    {   
     Node childNode = nodeList.item(i); 
     NodeList nodelist = childNode.getChildNodes(); 

     for(int ii = 0; ii < nodelist.getLength(); ii++) 
     {    
       node = nodelist.item(ii); 
       if(node.getNodeName().equalsIgnoreCase("description")) 
       { 
        node.getTextContent(); 
       }    
       else if(node.getNodeName().equalsIgnoreCase("taxAmount")) 
       { 
        NodeList taxAmountNodelist = node.getChildNodes(); 
        for(int iii = 0; iii < taxAmountNodelist.getLength(); iii++) 
        { 
         Node taxAmountNode = taxAmountNodelist.item(iii); 
         if(taxAmountNode.getNodeName().equalsIgnoreCase("amount")) 
         { 
          taxAmountNode.getTextContent();        
         } 
        } 
       }     
      else if(node.getNodeName().equalsIgnoreCase("taxcode")) 
      {        
       node.getTextContent();                
      } 
     } 


    }