我有一個像下面這樣的XML,如何檢索/提取XML元素屬性值
<?xml version="1.0" encoding="utf-8"?>
<PaymentElement>
<Payment seqID="3">
<TPayment>
<Status>status</Status>
</TPayment>
</Payment>
</PaymentElement>
的問題是如何檢索/提取物的SeqID值通過java是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);
}
結果爲空值3不來 – Swarne27
您是否嘗試過的類型轉換它作爲'String'? –
public static void main(String [] args)throws Exception { InputStream xml = new FileInputStream(「sample.xml」); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(xml); XPath xpath = XPathFactory.newInstance()。newXPath(); XPathExpression expr = xpath.compile(「/ PaymentElement/Payment/@ seqID」); Object result = expr.evaluate(doc,XPathConstants.STRING); System.out.println(result); } –