0

我有一个如下的 XML,

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

问题是如何通过 java 检索/提取 3 的 seqID 值。

我尝试了以下方法,但它不起作用。

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

2 回答 2

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

}
于 2013-01-24T08:25:30.240 回答
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
于 2013-01-24T08:33:04.523 回答