import java.io.FileOutputStream; import java.io.IOException; import java.io.FileNotFoundException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; /** * 根据传入的XML文件来获取并设置时间 * * * {talendTypes} String * * {Category} User Defined * * {param} string("xmlfile") input: The string need to be printed. * * {example} helloExemple("world") # hello world !. */ public static String getsetTime(String xiangmu) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,TransformerException,FileNotFoundException { String xfile="myxml/time.xml"; /*//只能类似于以下代码,其中传过来的参数 xiangmu就是下面的id值,time项可以有多行 <?xml version="1.0" encoding="UTF-8"?> <root> <time id="lvguan" now="2009-04-15 09:13:51"/> </root> */ SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String xintime=dateformat.format(new Date()); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); XPathFactory xpathFactory=XPathFactory.newInstance(); XPath xpath=xpathFactory.newXPath(); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder db=factory.newDocumentBuilder(); Document xmldoc=db.parse(new File(xfile)); xpathFactory=XPathFactory.newInstance(); xpath=xpathFactory.newXPath(); Element theBook=(Element)xpath.evaluate("/root/time[@id='"+xiangmu+"']",xmldoc, XPathConstants.NODE); //下面的行主要为更改项目内容时用到 //theBook.getElementsByTagName("now").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相当于xpath的".//price"。 String laotime=theBook.getAttribute("now"); theBook.setAttribute("now", xintime); //一下保存修改的XML文件 TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); DOMSource source=new DOMSource(); source.setNode(xmldoc); StreamResult result=new StreamResult(); result.setOutputStream(new FileOutputStream(xfile)); transformer.transform(source, result); return laotime; }