thieumao

XPATH sửa XML

Sep 19th, 2013
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.07 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package xulyxml;
  6.  
  7. import com.sun.org.apache.xml.internal.serialize.OutputFormat;
  8. import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
  9. import java.io.FileOutputStream;
  10. import java.text.DateFormat;
  11. import java.text.SimpleDateFormat;
  12. import java.util.Date;
  13. import javax.xml.parsers.DocumentBuilder;
  14. import javax.xml.parsers.DocumentBuilderFactory;
  15. import javax.xml.xpath.XPath;
  16. import javax.xml.xpath.XPathConstants;
  17. import javax.xml.xpath.XPathFactory;
  18. import org.w3c.dom.Document;
  19. import org.w3c.dom.Element;
  20. import org.w3c.dom.Node;
  21. import org.w3c.dom.NodeList;
  22. import org.xml.sax.InputSource;
  23.  
  24. public class XPathDemo {
  25.  
  26.     public static void main(String[] args) throws Exception {
  27.  
  28.         InputSource xml = new InputSource("MalwareData.xml");
  29.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  30.         DocumentBuilder db = dbf.newDocumentBuilder();
  31.         Document doc = db.parse(xml);
  32.  
  33.         XPathFactory xpf = XPathFactory.newInstance();
  34.         XPath xpath = xpf.newXPath();
  35.         String exp = "/malware/timestamp";
  36.  
  37.  
  38.  
  39.         NodeList names = (NodeList) xpath.evaluate(exp, doc, XPathConstants.NODESET);
  40.  
  41.         for (int i = 0; i < names.getLength(); i++) {
  42.             Element elem = (Element) names.item(i);
  43.  
  44.             //get current date time with Date()
  45.             Date date = new Date();
  46.             DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
  47.             String timeCurrent = dateFormat.format(date);
  48.  
  49.             // Sua file MalwareData.xml
  50.             names.item(i).setTextContent(timeCurrent);
  51.             System.err.println(elem.getTextContent());
  52.         }
  53.        
  54.        
  55.  
  56.         //Kết quả trả về là UtCung
  57.         //Ghi file xml
  58.  
  59.         FileOutputStream output = new FileOutputStream("MalwareData.xml");
  60.         XMLSerializer ser = new XMLSerializer(output, new OutputFormat(doc, "UTF-8", true));
  61.         ser.serialize(doc);
  62.         output.close();
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment