2013-01-24 90 views
0

我有一個像下面這樣的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); 
} 

回答

1
XPath xpath = XPathFactory.newInstance().newXPath(); 
XPathExpression expr = xpath.compile("/PaymentElement/Payment/@seqID"); 
Object result = expr.evaluate(doc, XPathConstants.STRING); 

result現在應該有3

完整的例子

import java.io.*; 
import javax.xml.xpath.*; 
import org.xml.sax.InputSource; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     InputStream inputStream = new FileInputStream("sample.xml"); 
     InputSource inputSource = new InputSource(inputStream); 
     XPath xpath = XPathFactory.newInstance().newXPath(); 
     XPathExpression expr = xpath.compile("/PaymentElement/Payment/@seqID"); 
     Object result = expr.evaluate(inputSource, XPathConstants.STRING); 
     System.out.println(result); 
    } 

} 
+0

結果爲空值3不來 – Swarne27

+0

您是否嘗試過的類型轉換它作爲'String'? –

+1

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); } –

1

嘗試

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 
+0

它不起作用,給第二行一個空指針 – Swarne27

+0

我在答案中拷貝了完整版本,再試一次 –