简体   繁体   中英

How to retrieve/extract XML element attribute value

I have an XML like the following,

<?xml version="1.0" encoding="utf-8"?>
    <PaymentElement>
        <Payment seqID="3">
            <TPayment>
                <Status>status</Status>
            </TPayment>
        </Payment>
    </PaymentElement>

The question is how do I retrieve/extract seqID value which is 3 out of this via java.

I have tried the following way, but it doesn't work.

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);
}
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/PaymentElement/Payment/@seqID");
Object result = expr.evaluate(doc, XPathConstants.STRING);

result should be having 3 now.

Full Example

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

}

try

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

output

 Payment seqID = 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM