如何检索/提取XML元素属性值

时间:2013-01-24 08:15:01

标签: java xml xml-parsing

我有一个类似以下的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);
}

2 个答案:

答案 0 :(得分: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);
    }

}

答案 1 :(得分: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