PDA

View Full Version : Tách XML = XPath giữ nguyên cấu trúc



mathswt
13-04-2006, 09:05
Giả sử có 1 file XML book.xml có nội dung như sau:
<book>
<title>Access 2000</title>
<cost>50USD</cost>
</book>

file testXPathJava.java
import javax.xml.xpath.*;
import org.xml.sax.*;
import com.sun.org.apache.xpath.internal.NodeSet;

public class testXPathJava {
public static void main(String[] args) {

try{
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/book";
InputSource inputSource = new InputSource("index2.xml");
String s = xpath.evaluate(expression, inputSource,XPathConstants.STRING).toString();
System.out.println(s);
}catch(Exception e){
System.out.println("Loi"+e);
}
}
}

thì output sẽ là:

Access 2000
50USD

Nếu muốn output bao gồm cả các tag thì làm thế nào?

VD:
<title>Access 2000</title>
<cost>50USD</cost>

Đang cần gấp lắm.
Any HELP/ADVISE would be greatly appreciated!!

Thanks in advance!!