我遇到了访问parentNode的孩子的挑战。下面是我正在使用的xml:
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>";
以下是我尝试的代码:
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);
}
请问如何在元素税中获得describe,taxAmt和taxCode?
答案 0 :(得分:0)
doc.getElementsByTagName("amount").item(0).getFirstChild().getNodeValue()
答案 1 :(得分:0)
这就是我能够解决我所拥有的问题的方法: DocumentBuilder builder = DocumentBuilderFactory.newInstance()。newDocumentBuilder(); InputSource src = new InputSource(); src.setCharacterStream(new StringReader(response)); 文档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();
}
}
}