我有一个类似以下的XML,
<?xml version="1.0" encoding="utf-8"?>
<PaymentElement>
<Payment seqID="3">
<TPayment>
<Status>status</Status>
</TPayment>
</Payment>
</PaymentElement>
问题是我如何通过java检索/提取seqID值,该值为3。
我尝试了以下方法,但是没有用。
InputStream xml = conn.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml);
NodeList list = doc.getElementsByTagName("PaymentElement");
for(int i=0; i<=list.getLength();i++){
NodeList paySeq=doc.getElementsByTagName("Payment seqID");
System.out.println("Payment seqID"+paySeq);
}
最佳答案
尝试
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("1.xml"));
Element e = (Element)doc.getDocumentElement().getElementsByTagName("Payment").item(0);
String id = e.getAttribute("seqID");
System.out.println("Payment seqID = " + id);
输出
Payment seqID = 3